title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Why MySQL NOT NULL shouldn’t be added to primary key field?
You do not need to add NOT NULL to primary key field because it gets NOT NULL automatically. Primary key is combination of both NOT NULL and Unique Key. Here is the demo of primary key field. Let us first create a table. The query to create a table is as follows: mysql> create table NotNullAddDemo -> ( -> Id int AUTO_INCREMENT, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.81 sec) In the above table, you do not need to add NOT NULL to primary key field because MySQL internally converts it into NOT NULL. To check if it is correct or not, use the following syntax. DESC yourTableName; Let us now check the above syntax to get the table description: mysql> desc NotNullAddDemo; The following is the output: +-------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | +-------+---------+------+-----+---------+----------------+ 1 row in set (0.07 sec) Look at the column Null, there is a value NO that means there is no NULL value. To check for NOT NULL, let us insert some NULL records in the table. This will allow NULL value but every time it counts the value from 1. The query to insert records in the table. mysql> insert into NotNullAddDemo values(NULL); Query OK, 1 row affected (0.12 sec) mysql> insert into NotNullAddDemo values(NULL); Query OK, 1 row affected (0.45 sec) After inserting two NULL values for primary key, if you try to insert value 1, then an error will generate. This is because MySQL counts first NULL value as 1 and second NULL value as 2 and so on. The error is as follows if you will now try to insert 1: mysql> insert into NotNullAddDemo values(1); ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY' If you insert value 3 then it will accept: mysql> insert into NotNullAddDemo values(3); Query OK, 1 row affected (0.21 sec) mysql> insert into NotNullAddDemo values(NULL); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from NotNullAddDemo; The following is the output: +----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | +----+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1215, "s": 1062, "text": "You do not need to add NOT NULL to primary key field because it gets NOT NULL automatically. Primary key is combination of both NOT NULL and Unique Key." }, { "code": null, "e": 1326, "s": 1215, "text": "Here is the demo of primary key field. Let us first create a table. The query to create a table is as follows:" }, { "code": null, "e": 1466, "s": 1326, "text": "mysql> create table NotNullAddDemo\n -> (\n -> Id int AUTO_INCREMENT,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.81 sec)" }, { "code": null, "e": 1651, "s": 1466, "text": "In the above table, you do not need to add NOT NULL to primary key field because MySQL internally converts it into NOT NULL. To check if it is correct or not, use the following syntax." }, { "code": null, "e": 1671, "s": 1651, "text": "DESC yourTableName;" }, { "code": null, "e": 1735, "s": 1671, "text": "Let us now check the above syntax to get the table description:" }, { "code": null, "e": 1763, "s": 1735, "text": "mysql> desc NotNullAddDemo;" }, { "code": null, "e": 1792, "s": 1763, "text": "The following is the output:" }, { "code": null, "e": 2116, "s": 1792, "text": "+-------+---------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n+-------+---------+------+-----+---------+----------------+\n1 row in set (0.07 sec)" }, { "code": null, "e": 2196, "s": 2116, "text": "Look at the column Null, there is a value NO that means there is no NULL value." }, { "code": null, "e": 2377, "s": 2196, "text": "To check for NOT NULL, let us insert some NULL records in the table. This will allow NULL value but every time it counts the value from 1. The query to insert records in the table." }, { "code": null, "e": 2545, "s": 2377, "text": "mysql> insert into NotNullAddDemo values(NULL);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into NotNullAddDemo values(NULL);\nQuery OK, 1 row affected (0.45 sec)" }, { "code": null, "e": 2742, "s": 2545, "text": "After inserting two NULL values for primary key, if you try to insert value 1, then an error will generate. This is because MySQL counts first NULL value as 1 and second NULL value as 2 and so on." }, { "code": null, "e": 2799, "s": 2742, "text": "The error is as follows if you will now try to insert 1:" }, { "code": null, "e": 2902, "s": 2799, "text": "mysql> insert into NotNullAddDemo values(1);\nERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'" }, { "code": null, "e": 2945, "s": 2902, "text": "If you insert value 3 then it will accept:" }, { "code": null, "e": 3110, "s": 2945, "text": "mysql> insert into NotNullAddDemo values(3);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into NotNullAddDemo values(NULL);\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 3194, "s": 3110, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 3230, "s": 3194, "text": "mysql> select *from NotNullAddDemo;" }, { "code": null, "e": 3259, "s": 3230, "text": "The following is the output:" }, { "code": null, "e": 3340, "s": 3259, "text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+----+\n4 rows in set (0.00 sec)" } ]
Full-Stack AI: Building a UI for Your Latest AI Project in No Time at All | by Posey | Towards Data Science
Let’s see how we can build a Convolutional Neural Network into a user-friendly application with a clean UI. How can we integrate both training and predictions into an easy to use interface? More importantly, how can we do this without spending countless hours on technology we may not be great at. We’re Data Scientists, Machine Learning Engineers, and analysts, not Front-End Developers. And if you ARE a Front-End Dev, you may still be interested to see how streamlined this approach is. Our stated objective is to identify the type of animal from various pictures of different animals. Let’s see how we can do this. First things first, we need to find some data. For the purposes of this application we used https://www.kaggle.com/alessiocorrado99/animals10 This is a 1.2 GB dataset with thousands of images across 10 classes of animals. Since we’re using Keras’ ImageGenerator for this, we need to split our dataset accordingly. First, split the data into Training and Test folders. In each folder your labels will be the names of each folder as the class name. For example, all the pictures of cats should be in a folder named cat, horse in a folder named horse, etc. Next, we start model building. After iterating on parameters to see what worked best, here’s where the CNN’s parameters landed: You can find the rest of the CNN’s code in the Github link at the end of the article. This is where things get interesting. How can we integrate both training and predictions into an easy to use interface? More importantly, how can we do this without spending countless hours on technology we may not be great at. We’re Data Scientists, Machine Learning Engineers, and analysts, not Front-End Developers. The answer is Streamlit. Streamlit works with all of your favorite Python-based libraries. You can easily integrate your Machine Learning models with a clean UI. You can then easily deploy the application from Streamlit onto your platform of choice: AWS, Azure, etc... Let’s walk through it step by step. First things first, install Streamlit. pip install streamlit Now, let’s import the necessary libraries and get this show on the road. The first thing we did is import our libraries and construct a sidebar for our otherwise empty application. The above code will produce this: Next, let’s add a selectbox for picking images from a folder local to the project... from os import listdirfrom os.path import isfile, joinonlyfiles = [f for f in listdir("C:/Users/Luke/Desktop/StreamlitDemo/Data/Test/") if isfile(join("C:/Users/Luke/Desktop/StreamlitDemo/Data/Test/", f))]imageselect = st.sidebar.selectbox("Pick an image.", onlyfiles) From here, we can use that selected image to display a picture on the screen... Now that we’ve got our image on the screen, let’s incorporate our Neural Network... In Training.py we’ve built our neural network and can use those functions in our Demo.py (main Streamlit file) to add training and predicting power to the application. First, the training portion... import Training st.sidebar.title("Train Neural Network")if st.sidebar.button('Train CNN'): Training.train() Now, let’s add the prediction portion... I hope this inspired you to build your own project with the above stack. I think it’s a really great tool for us data people who don’t want to drown in HTML or some modern tech stack. Let’s continue the convo in the comments or feel free to tweet at me. For the full code to this project: github.com Let’s continue the conversation on Twitter. To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership
[ { "code": null, "e": 662, "s": 172, "text": "Let’s see how we can build a Convolutional Neural Network into a user-friendly application with a clean UI. How can we integrate both training and predictions into an easy to use interface? More importantly, how can we do this without spending countless hours on technology we may not be great at. We’re Data Scientists, Machine Learning Engineers, and analysts, not Front-End Developers. And if you ARE a Front-End Dev, you may still be interested to see how streamlined this approach is." }, { "code": null, "e": 791, "s": 662, "text": "Our stated objective is to identify the type of animal from various pictures of different animals. Let’s see how we can do this." }, { "code": null, "e": 933, "s": 791, "text": "First things first, we need to find some data. For the purposes of this application we used https://www.kaggle.com/alessiocorrado99/animals10" }, { "code": null, "e": 1013, "s": 933, "text": "This is a 1.2 GB dataset with thousands of images across 10 classes of animals." }, { "code": null, "e": 1345, "s": 1013, "text": "Since we’re using Keras’ ImageGenerator for this, we need to split our dataset accordingly. First, split the data into Training and Test folders. In each folder your labels will be the names of each folder as the class name. For example, all the pictures of cats should be in a folder named cat, horse in a folder named horse, etc." }, { "code": null, "e": 1473, "s": 1345, "text": "Next, we start model building. After iterating on parameters to see what worked best, here’s where the CNN’s parameters landed:" }, { "code": null, "e": 1559, "s": 1473, "text": "You can find the rest of the CNN’s code in the Github link at the end of the article." }, { "code": null, "e": 1878, "s": 1559, "text": "This is where things get interesting. How can we integrate both training and predictions into an easy to use interface? More importantly, how can we do this without spending countless hours on technology we may not be great at. We’re Data Scientists, Machine Learning Engineers, and analysts, not Front-End Developers." }, { "code": null, "e": 2147, "s": 1878, "text": "The answer is Streamlit. Streamlit works with all of your favorite Python-based libraries. You can easily integrate your Machine Learning models with a clean UI. You can then easily deploy the application from Streamlit onto your platform of choice: AWS, Azure, etc..." }, { "code": null, "e": 2183, "s": 2147, "text": "Let’s walk through it step by step." }, { "code": null, "e": 2222, "s": 2183, "text": "First things first, install Streamlit." }, { "code": null, "e": 2244, "s": 2222, "text": "pip install streamlit" }, { "code": null, "e": 2317, "s": 2244, "text": "Now, let’s import the necessary libraries and get this show on the road." }, { "code": null, "e": 2459, "s": 2317, "text": "The first thing we did is import our libraries and construct a sidebar for our otherwise empty application. The above code will produce this:" }, { "code": null, "e": 2544, "s": 2459, "text": "Next, let’s add a selectbox for picking images from a folder local to the project..." }, { "code": null, "e": 2813, "s": 2544, "text": "from os import listdirfrom os.path import isfile, joinonlyfiles = [f for f in listdir(\"C:/Users/Luke/Desktop/StreamlitDemo/Data/Test/\") if isfile(join(\"C:/Users/Luke/Desktop/StreamlitDemo/Data/Test/\", f))]imageselect = st.sidebar.selectbox(\"Pick an image.\", onlyfiles)" }, { "code": null, "e": 2893, "s": 2813, "text": "From here, we can use that selected image to display a picture on the screen..." }, { "code": null, "e": 2977, "s": 2893, "text": "Now that we’ve got our image on the screen, let’s incorporate our Neural Network..." }, { "code": null, "e": 3145, "s": 2977, "text": "In Training.py we’ve built our neural network and can use those functions in our Demo.py (main Streamlit file) to add training and predicting power to the application." }, { "code": null, "e": 3176, "s": 3145, "text": "First, the training portion..." }, { "code": null, "e": 3289, "s": 3176, "text": "import Training st.sidebar.title(\"Train Neural Network\")if st.sidebar.button('Train CNN'): Training.train()" }, { "code": null, "e": 3330, "s": 3289, "text": "Now, let’s add the prediction portion..." }, { "code": null, "e": 3584, "s": 3330, "text": "I hope this inspired you to build your own project with the above stack. I think it’s a really great tool for us data people who don’t want to drown in HTML or some modern tech stack. Let’s continue the convo in the comments or feel free to tweet at me." }, { "code": null, "e": 3619, "s": 3584, "text": "For the full code to this project:" }, { "code": null, "e": 3630, "s": 3619, "text": "github.com" }, { "code": null, "e": 3674, "s": 3630, "text": "Let’s continue the conversation on Twitter." } ]
Can We Use Machine Learning To Generate Text Adventure Stories? | by Jesse Freeman | Towards Data Science
Last year I started working on a little text adventure game for a 48-hour game jam called Ludum Dare. I take part in it a few times a year and even did the keynote once. While I was able to build a simple text adventure game engine in a day, I started losing steam when it came to creating the content to make it interesting. Fast forward 6 months, plus a career change into machine learning, and I became interested in seeing if I could train a neural network to generate a backstory for my unfinished text adventure game. My goal was to help augment the randomly generated room descriptions with a bit of narrative from an AI gone rogue. I based the game on one of my favorite first-person shooters (FPS) from the 90s, Marathon. Marathon was created by Bungie, well before it released Halo and Destiny. In Marathon, there were three AIs and the main one, Durandal, became “rampant,” which is a fancy term for going crazy. Unlike similar FPS games of the time such as Doom, Marathon had a rich story you could read through terminals scattered throughout the levels. These terminals not only instructed you of tasks but also deepened the plot as you progressed through the game. Now there are lots of great examples of neural networks that have been trained to create text-based content such as song lyrics, Shakespeare poems, and more. Since Marathon contained so much text in the terminals across its three games, I thought it would be an excellent candidate to use an open-source project called textgenrnn, with the help of some tools I use to automate my deep learning workflow, to see what I could create. Plus, since the AI in the game goes crazy, I hoped that even if the generated text didn’t make sense, it would still fit into the theme of the text adventure game I was creating. The following is an account of my experimentation, the results, and notes on how to run the project on your own from my git repo here. Luckily, Marathon’s story is well documented online here. If you haven’t played the game before, it’s worth checking out. You can run a more modern version of it called Alpha One here. With that in mind, to train a textgenrnn model, I had to create a dataset from scratch. There wasn’t an easy way to automate this, so I went through all of the game terminals from the site and copied them into a text file by hand. You can train textgenrnn with a small set of text but the more you give it, the better it should learn. I tried a few different variations on formatting the game text, but in the end, I had to go in by hand and remove text blocks that negatively impact the training. Even terminal text like this, which looks like random characters placed together, actually contains a story. In its current format, the text would throw off the training since we are going to analyze individual words which require spaces between them. In the end, to create a cleaner dataset, I decided to skip these kinds of text blocks. Because this was rather time-consuming, I ended up using the first game’s story. Here is a link to the source file I trained on in the git project. I began by cloning textgenrnn from GitHub and opening it up in PyCharm. Once I had the project opened, I created a new Python interpreter and installed the requirements defined in the setup.py script. You’ll also want to install Tensorflow which wasn’t in the list of dependencies. I ended up creating a new requirements.txt with the following: The project is well documented and comes with some examples, but I chose to delete them and start with a clean project folder. I removed all the content from the datasets, output, and weights folders since I would generate those with the new dataset. Then I removed the setup.py file since I no longer needed it. The only thing left to do was add my new Marathon terminal text dataset to the appropriate folder and begin creating the scripts to run the training. Before I could do that, I needed to create a config file I could share between my training and text generating scripts. To do this, I created a config.py script to the root of the project with the following code: While you can train a model or generate text by passing these values in directly, I find it helped to keep this external so I could tweak it a bit easier while training. With the new config file ready, it was time to create the scripts I needed to train and generate out text. With all of the configuration values in their own file, I was able to create a simple train.py script to run the actual training. Here is what the code looks like: At a high level, I create a new instance of textgenrnn, set up the path to the output folder, and finally call the train function and supply the arguments it needs. At this point, you can run the script and monitor some of the early output from the terminal window: At around the 10th epoch, the text is getting better, but we won’t see the actual results until we generate more substantial amounts of text from the trained model in the outputs folder. To generate more text, I created a generate.py script with the following code: As you can see, I set up textgenrnn by supplying it with the three files created during training: weights, vocab, and config. From there, we tell textgenrnn to create a new file using an array of temperature values, the number of steps, and the maximum length of the generated text. After running this script, it generates a new text file in the outputs folder with the generated text: Now that I had everything I needed to begin training and validating the quality of the generated text. Let’s take a look at what it produced. At this point, it’s relatively easy to see what kind of results we can expect. Here are a few samples I began experimenting with. 1 epoch, RNN size of 128 and 2 RNN layers produced the following: vacuum-withyou* *incoming **-<transfer,strengthgivesarea ofa- ,to*public.oppressive *~<* * * * * * * * jump * * * * * * * * * * * pad * * *durandalmessage* At first, it wasn’t creating anything interesting. I expected that with only a single epoch. Here is what happened when I increased the training to 10 epochs with the same settings as above: * * * incoming message from * * ** * * incoming message * * *< 39 - < 46 . . . 299 >* * * end of message * * * *he , , and crist the from closing his , and closing five was the of arms . on the discarding elevators century* * * end when message * * * *< security breached - excerpts >f terminal . . 17 . . . 198 >* * * end of message * * *< security breached - - < 33 . 12 . . . 128 >for the the of may fourth* * * end message * * *teleport whenit is is is is . . . i am am able that to to to my sensory eyes the you you you your your a " see philosophical may your your a21h . . . . " . . 223 > Things are starting to get a bit more interesting. The model can generate full sentences, it learned that messages usually begin and end with some form of “incoming/end message” and it can create some of the fake IP addresses associated with specific types of terminal messages. It’s also good at beginning and ending sections of text with quotes, but the text doesn’t make a whole lot of sense. Finally, I wanted to see if more epochs would help, so I increased the number to 40 and kept the same settings as a baseline. Here is what it generated: you have not completed your mission . you may be be not the such here . but i ' ll want to to to friend . if you must into the this to of transmission it would be be a fighter day . . . fighter . held symbolic significance for the . the time that time that hadmartian skieshowever , due to to the marathon ' s teleporters . .< unauthorized access - alarm 2521 - >be careful . everything not not not as to , and or , and nearly active to your your maintenance maintenance . .the pfhor seem to have enslaved a number of other races : : races as of have they been been been been off by compilers for for and alien .the invaders seem to to be interested in the marathon . gheritt s something something one as from about he ' s ' s ' pht , . even hard . . to the was was . rat the the the the the crist shuttle . has , and and at the just than the the after the the Now we are starting to get complete sentences, which appear to make more sense in paragraphs. The challenge, of course, is that at this point, I was stabbing in the dark trying to understand which values help train better models. Unfortunately, there was a lot of trial and error until I started finding values I felt were producing better results. To help monitor the training, I wanted to add MissingLink.ai’s SDK to the project to monitor my experiments. Full disclosure, I work for Missinglink, and since I had a vested interest in completing my text adventure game, I became interested in seeing how I could optimize the model during training to identify what values made a difference. So I created a new missinglink branch and added a few lines of code to the project’s textgenrnn.py script starting with importing the SDK, configuring a project to run the experiment in, and defining the Keras callback: Also, I needed to feed the new callback into the model_t.fit_generator() method: With these modifications, I was now able to run the experiment and monitor the results on the MissingLink dashboard. I started with my last experiment at 40 epochs as a baseline before moving onto the next round of training. After trying a few different settings, I finally settled on 4 RNN layers, bidirectional set to true and 100 epochs. I also increased the train size to .9 which yielded the following loss: Once I was happy with the improved model, I was able to generate better text. Let’s take a look at the final results. After a lot of experimenting, I was able to come up with some blocks of text that felt coherent enough to pass as the ramblings of a crazy AI. Example A: From Marathon Gheritt had a good life, so much time, so much time. He had loved swimming, turning, beating. He had loved the tingle in his hands and feet, his inability to kill his nemesis. Once he had fallen down the stairs, and just for a moment, his hands came to rest on the carpet of the stairs. In that instant, his body had frozen, floating over the stairs, safe from falling, but the moment didn’t last. The ocean crashed about him, his hands torn free from the sandy bottom, his body flipping, falling. Example B: Generated gheritt had a good life , so much on that will be killed . i saw the make one in a wicked computer — and we must don ‘ t remember them any time you .i have received a preliminary report from some members of them . the only computer system . “ it was quite simple . “ a white thought syndrome suffering if the uesc ‘ s ‘ pht even stopped their efforts . I was surprised at how close this was getting. I think with more data, editing the grammar, and a smart integration into the game, this is probably a viable solution for generating some of the background story content. The goal would be to blend randomly generated text, neural network generated text, and handwritten text into a more seamless experience. With that in mind, I plan on integrating this into the game and mixing it with more task-oriented text that outlines objectives, similar to how Marathon terminals work in the original game. I’d say this little experiment was a success. I need to spend a little more time building a better dataset that includes both Marathon 2 & 3’s terminals. I also want to see if I can eventually get a coherent story out of the model. There is still tweaking to do between the config file and the dataset. However, even after these early experiments, I think the results are promising. Finally, it’s worth mentioning that textgenrnn is an old project. There have been even more advancements in text generation such as OpenAI’s GPT-2. I could see myself continuing to experiment with training a neural network to generate text for more of my procedurally generated games. If you’d like to know more about this project and my work at MissingLink.ai, feel free to leave a comment below or follow me on Twitter and send me a message.
[ { "code": null, "e": 497, "s": 171, "text": "Last year I started working on a little text adventure game for a 48-hour game jam called Ludum Dare. I take part in it a few times a year and even did the keynote once. While I was able to build a simple text adventure game engine in a day, I started losing steam when it came to creating the content to make it interesting." }, { "code": null, "e": 902, "s": 497, "text": "Fast forward 6 months, plus a career change into machine learning, and I became interested in seeing if I could train a neural network to generate a backstory for my unfinished text adventure game. My goal was to help augment the randomly generated room descriptions with a bit of narrative from an AI gone rogue. I based the game on one of my favorite first-person shooters (FPS) from the 90s, Marathon." }, { "code": null, "e": 1350, "s": 902, "text": "Marathon was created by Bungie, well before it released Halo and Destiny. In Marathon, there were three AIs and the main one, Durandal, became “rampant,” which is a fancy term for going crazy. Unlike similar FPS games of the time such as Doom, Marathon had a rich story you could read through terminals scattered throughout the levels. These terminals not only instructed you of tasks but also deepened the plot as you progressed through the game." }, { "code": null, "e": 1961, "s": 1350, "text": "Now there are lots of great examples of neural networks that have been trained to create text-based content such as song lyrics, Shakespeare poems, and more. Since Marathon contained so much text in the terminals across its three games, I thought it would be an excellent candidate to use an open-source project called textgenrnn, with the help of some tools I use to automate my deep learning workflow, to see what I could create. Plus, since the AI in the game goes crazy, I hoped that even if the generated text didn’t make sense, it would still fit into the theme of the text adventure game I was creating." }, { "code": null, "e": 2096, "s": 1961, "text": "The following is an account of my experimentation, the results, and notes on how to run the project on your own from my git repo here." }, { "code": null, "e": 2512, "s": 2096, "text": "Luckily, Marathon’s story is well documented online here. If you haven’t played the game before, it’s worth checking out. You can run a more modern version of it called Alpha One here. With that in mind, to train a textgenrnn model, I had to create a dataset from scratch. There wasn’t an easy way to automate this, so I went through all of the game terminals from the site and copied them into a text file by hand." }, { "code": null, "e": 2779, "s": 2512, "text": "You can train textgenrnn with a small set of text but the more you give it, the better it should learn. I tried a few different variations on formatting the game text, but in the end, I had to go in by hand and remove text blocks that negatively impact the training." }, { "code": null, "e": 3266, "s": 2779, "text": "Even terminal text like this, which looks like random characters placed together, actually contains a story. In its current format, the text would throw off the training since we are going to analyze individual words which require spaces between them. In the end, to create a cleaner dataset, I decided to skip these kinds of text blocks. Because this was rather time-consuming, I ended up using the first game’s story. Here is a link to the source file I trained on in the git project." }, { "code": null, "e": 3611, "s": 3266, "text": "I began by cloning textgenrnn from GitHub and opening it up in PyCharm. Once I had the project opened, I created a new Python interpreter and installed the requirements defined in the setup.py script. You’ll also want to install Tensorflow which wasn’t in the list of dependencies. I ended up creating a new requirements.txt with the following:" }, { "code": null, "e": 3924, "s": 3611, "text": "The project is well documented and comes with some examples, but I chose to delete them and start with a clean project folder. I removed all the content from the datasets, output, and weights folders since I would generate those with the new dataset. Then I removed the setup.py file since I no longer needed it." }, { "code": null, "e": 4287, "s": 3924, "text": "The only thing left to do was add my new Marathon terminal text dataset to the appropriate folder and begin creating the scripts to run the training. Before I could do that, I needed to create a config file I could share between my training and text generating scripts. To do this, I created a config.py script to the root of the project with the following code:" }, { "code": null, "e": 4564, "s": 4287, "text": "While you can train a model or generate text by passing these values in directly, I find it helped to keep this external so I could tweak it a bit easier while training. With the new config file ready, it was time to create the scripts I needed to train and generate out text." }, { "code": null, "e": 4728, "s": 4564, "text": "With all of the configuration values in their own file, I was able to create a simple train.py script to run the actual training. Here is what the code looks like:" }, { "code": null, "e": 4994, "s": 4728, "text": "At a high level, I create a new instance of textgenrnn, set up the path to the output folder, and finally call the train function and supply the arguments it needs. At this point, you can run the script and monitor some of the early output from the terminal window:" }, { "code": null, "e": 5181, "s": 4994, "text": "At around the 10th epoch, the text is getting better, but we won’t see the actual results until we generate more substantial amounts of text from the trained model in the outputs folder." }, { "code": null, "e": 5260, "s": 5181, "text": "To generate more text, I created a generate.py script with the following code:" }, { "code": null, "e": 5646, "s": 5260, "text": "As you can see, I set up textgenrnn by supplying it with the three files created during training: weights, vocab, and config. From there, we tell textgenrnn to create a new file using an array of temperature values, the number of steps, and the maximum length of the generated text. After running this script, it generates a new text file in the outputs folder with the generated text:" }, { "code": null, "e": 5788, "s": 5646, "text": "Now that I had everything I needed to begin training and validating the quality of the generated text. Let’s take a look at what it produced." }, { "code": null, "e": 5918, "s": 5788, "text": "At this point, it’s relatively easy to see what kind of results we can expect. Here are a few samples I began experimenting with." }, { "code": null, "e": 5984, "s": 5918, "text": "1 epoch, RNN size of 128 and 2 RNN layers produced the following:" }, { "code": null, "e": 6140, "s": 5984, "text": "vacuum-withyou* *incoming **-<transfer,strengthgivesarea ofa- ,to*public.oppressive *~<* * * * * * * * jump * * * * * * * * * * * pad * * *durandalmessage*" }, { "code": null, "e": 6233, "s": 6140, "text": "At first, it wasn’t creating anything interesting. I expected that with only a single epoch." }, { "code": null, "e": 6331, "s": 6233, "text": "Here is what happened when I increased the training to 10 epochs with the same settings as above:" }, { "code": null, "e": 6927, "s": 6331, "text": "* * * incoming message from * * ** * * incoming message * * *< 39 - < 46 . . . 299 >* * * end of message * * * *he , , and crist the from closing his , and closing five was the of arms . on the discarding elevators century* * * end when message * * * *< security breached - excerpts >f terminal . . 17 . . . 198 >* * * end of message * * *< security breached - - < 33 . 12 . . . 128 >for the the of may fourth* * * end message * * *teleport whenit is is is is . . . i am am able that to to to my sensory eyes the you you you your your a \" see philosophical may your your a21h . . . . \" . . 223 >" }, { "code": null, "e": 7323, "s": 6927, "text": "Things are starting to get a bit more interesting. The model can generate full sentences, it learned that messages usually begin and end with some form of “incoming/end message” and it can create some of the fake IP addresses associated with specific types of terminal messages. It’s also good at beginning and ending sections of text with quotes, but the text doesn’t make a whole lot of sense." }, { "code": null, "e": 7476, "s": 7323, "text": "Finally, I wanted to see if more epochs would help, so I increased the number to 40 and kept the same settings as a baseline. Here is what it generated:" }, { "code": null, "e": 8337, "s": 7476, "text": "you have not completed your mission . you may be be not the such here . but i ' ll want to to to friend . if you must into the this to of transmission it would be be a fighter day . . . fighter . held symbolic significance for the . the time that time that hadmartian skieshowever , due to to the marathon ' s teleporters . .< unauthorized access - alarm 2521 - >be careful . everything not not not as to , and or , and nearly active to your your maintenance maintenance . .the pfhor seem to have enslaved a number of other races : : races as of have they been been been been off by compilers for for and alien .the invaders seem to to be interested in the marathon . gheritt s something something one as from about he ' s ' s ' pht , . even hard . . to the was was . rat the the the the the crist shuttle . has , and and at the just than the the after the the" }, { "code": null, "e": 8686, "s": 8337, "text": "Now we are starting to get complete sentences, which appear to make more sense in paragraphs. The challenge, of course, is that at this point, I was stabbing in the dark trying to understand which values help train better models. Unfortunately, there was a lot of trial and error until I started finding values I felt were producing better results." }, { "code": null, "e": 9028, "s": 8686, "text": "To help monitor the training, I wanted to add MissingLink.ai’s SDK to the project to monitor my experiments. Full disclosure, I work for Missinglink, and since I had a vested interest in completing my text adventure game, I became interested in seeing how I could optimize the model during training to identify what values made a difference." }, { "code": null, "e": 9248, "s": 9028, "text": "So I created a new missinglink branch and added a few lines of code to the project’s textgenrnn.py script starting with importing the SDK, configuring a project to run the experiment in, and defining the Keras callback:" }, { "code": null, "e": 9329, "s": 9248, "text": "Also, I needed to feed the new callback into the model_t.fit_generator() method:" }, { "code": null, "e": 9554, "s": 9329, "text": "With these modifications, I was now able to run the experiment and monitor the results on the MissingLink dashboard. I started with my last experiment at 40 epochs as a baseline before moving onto the next round of training." }, { "code": null, "e": 9742, "s": 9554, "text": "After trying a few different settings, I finally settled on 4 RNN layers, bidirectional set to true and 100 epochs. I also increased the train size to .9 which yielded the following loss:" }, { "code": null, "e": 9860, "s": 9742, "text": "Once I was happy with the improved model, I was able to generate better text. Let’s take a look at the final results." }, { "code": null, "e": 10003, "s": 9860, "text": "After a lot of experimenting, I was able to come up with some blocks of text that felt coherent enough to pass as the ramblings of a crazy AI." }, { "code": null, "e": 10028, "s": 10003, "text": "Example A: From Marathon" }, { "code": null, "e": 10526, "s": 10028, "text": "Gheritt had a good life, so much time, so much time. He had loved swimming, turning, beating. He had loved the tingle in his hands and feet, his inability to kill his nemesis. Once he had fallen down the stairs, and just for a moment, his hands came to rest on the carpet of the stairs. In that instant, his body had frozen, floating over the stairs, safe from falling, but the moment didn’t last. The ocean crashed about him, his hands torn free from the sandy bottom, his body flipping, falling." }, { "code": null, "e": 10547, "s": 10526, "text": "Example B: Generated" }, { "code": null, "e": 10900, "s": 10547, "text": "gheritt had a good life , so much on that will be killed . i saw the make one in a wicked computer — and we must don ‘ t remember them any time you .i have received a preliminary report from some members of them . the only computer system . “ it was quite simple . “ a white thought syndrome suffering if the uesc ‘ s ‘ pht even stopped their efforts ." }, { "code": null, "e": 11446, "s": 10900, "text": "I was surprised at how close this was getting. I think with more data, editing the grammar, and a smart integration into the game, this is probably a viable solution for generating some of the background story content. The goal would be to blend randomly generated text, neural network generated text, and handwritten text into a more seamless experience. With that in mind, I plan on integrating this into the game and mixing it with more task-oriented text that outlines objectives, similar to how Marathon terminals work in the original game." }, { "code": null, "e": 12114, "s": 11446, "text": "I’d say this little experiment was a success. I need to spend a little more time building a better dataset that includes both Marathon 2 & 3’s terminals. I also want to see if I can eventually get a coherent story out of the model. There is still tweaking to do between the config file and the dataset. However, even after these early experiments, I think the results are promising. Finally, it’s worth mentioning that textgenrnn is an old project. There have been even more advancements in text generation such as OpenAI’s GPT-2. I could see myself continuing to experiment with training a neural network to generate text for more of my procedurally generated games." } ]
SOAP - Examples
In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request has a QuotationName parameter, and a Quotation will be returned in the response. The namespace for the function is defined in http://www.xyz.org/quotation address. Here is the SOAP request − POST /Quotation HTTP/1.0 Host: www.xyz.org Content-Type: text/xml; charset = utf-8 Content-Length: nnn <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Body xmlns:m = "http://www.xyz.org/quotations"> <m:GetQuotation> <m:QuotationsName>MiscroSoft</m:QuotationsName> </m:GetQuotation> </SOAP-ENV:Body> </SOAP-ENV:Envelope> A corresponding SOAP response looks like − HTTP/1.0 200 OK Content-Type: text/xml; charset = utf-8 Content-Length: nnn <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Body xmlns:m = "http://www.xyz.org/quotation"> <m:GetQuotationResponse> <m:Quotation>Here is the quotation</m:Quotation> </m:GetQuotationResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> 8 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 1888, "s": 1714, "text": "In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request has a QuotationName parameter, and a Quotation will be returned in the response." }, { "code": null, "e": 1971, "s": 1888, "text": "The namespace for the function is defined in http://www.xyz.org/quotation address." }, { "code": null, "e": 1998, "s": 1971, "text": "Here is the SOAP request −" }, { "code": null, "e": 2485, "s": 1998, "text": "POST /Quotation HTTP/1.0\nHost: www.xyz.org\nContent-Type: text/xml; charset = utf-8\nContent-Length: nnn\n\n<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Body xmlns:m = \"http://www.xyz.org/quotations\">\n <m:GetQuotation>\n <m:QuotationsName>MiscroSoft</m:QuotationsName>\n </m:GetQuotation>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 2528, "s": 2485, "text": "A corresponding SOAP response looks like −" }, { "code": null, "e": 3004, "s": 2528, "text": "HTTP/1.0 200 OK\nContent-Type: text/xml; charset = utf-8\nContent-Length: nnn\n\n<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Body xmlns:m = \"http://www.xyz.org/quotation\">\n <m:GetQuotationResponse>\n <m:Quotation>Here is the quotation</m:Quotation>\n </m:GetQuotationResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 3036, "s": 3004, "text": "\n 8 Lectures \n 4 hours \n" }, { "code": null, "e": 3053, "s": 3036, "text": " Frahaan Hussain" }, { "code": null, "e": 3060, "s": 3053, "text": " Print" }, { "code": null, "e": 3071, "s": 3060, "text": " Add Notes" } ]
PyQt5 - Toggle Button - GeeksforGeeks
22 Apr, 2020 In PyQt5 a toggle button is basically is the push button in a special state. Push button is a button when we press it do some task and get back to the normal state it is similar to key board key when we press it, it do some thing and when we release it, it comes back to its original form. ToggleButton is a type of push button, but it has two states i.e on and off when we press it, it don’t comes back to the original state. Toggle button is similar to a electricity switch when we press it, it remains on and when we turn it off it remains in off position. In order to create toggle button we have to do the following: Create a push button.Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box.Set calling method which get called when button is pressed.In calling method check if the button is checked or not.If button is checked change its color else set the default color to it. Create a push button. Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box. Set calling method which get called when button is pressed. In calling method check if the button is checked or not. If button is checked change its color else set the default color to it. Below is the implementation. # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a push button self.button = QPushButton("Toggle", self) # setting geometry of button self.button.setGeometry(200, 150, 100, 40) # setting checkable to true self.button.setCheckable(True) # setting calling method by button self.button.clicked.connect(self.changeColor) # setting default color of button to light-grey self.button.setStyleSheet("background-color : lightgrey") # show all the widgets self.update() self.show() # method called by button def changeColor(self): # if button is checked if self.button.isChecked(): # setting background color to light-blue self.button.setStyleSheet("background-color : lightblue") # if it is unchecked else: # set background color back to light-grey self.button.setStyleSheet("background-color : lightgrey") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24517, "s": 24489, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24807, "s": 24517, "text": "In PyQt5 a toggle button is basically is the push button in a special state. Push button is a button when we press it do some task and get back to the normal state it is similar to key board key when we press it, it do some thing and when we release it, it comes back to its original form." }, { "code": null, "e": 25077, "s": 24807, "text": "ToggleButton is a type of push button, but it has two states i.e on and off when we press it, it don’t comes back to the original state. Toggle button is similar to a electricity switch when we press it, it remains on and when we turn it off it remains in off position." }, { "code": null, "e": 25139, "s": 25077, "text": "In order to create toggle button we have to do the following:" }, { "code": null, "e": 25472, "s": 25139, "text": "Create a push button.Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box.Set calling method which get called when button is pressed.In calling method check if the button is checked or not.If button is checked change its color else set the default color to it." }, { "code": null, "e": 25494, "s": 25472, "text": "Create a push button." }, { "code": null, "e": 25620, "s": 25494, "text": "Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box." }, { "code": null, "e": 25680, "s": 25620, "text": "Set calling method which get called when button is pressed." }, { "code": null, "e": 25737, "s": 25680, "text": "In calling method check if the button is checked or not." }, { "code": null, "e": 25809, "s": 25737, "text": "If button is checked change its color else set the default color to it." }, { "code": null, "e": 25838, "s": 25809, "text": "Below is the implementation." }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") # setting geometry self.setGeometry(100, 100, 600, 400) # creating a push button self.button = QPushButton(\"Toggle\", self) # setting geometry of button self.button.setGeometry(200, 150, 100, 40) # setting checkable to true self.button.setCheckable(True) # setting calling method by button self.button.clicked.connect(self.changeColor) # setting default color of button to light-grey self.button.setStyleSheet(\"background-color : lightgrey\") # show all the widgets self.update() self.show() # method called by button def changeColor(self): # if button is checked if self.button.isChecked(): # setting background color to light-blue self.button.setStyleSheet(\"background-color : lightblue\") # if it is unchecked else: # set background color back to light-grey self.button.setStyleSheet(\"background-color : lightgrey\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27275, "s": 25838, "text": null }, { "code": null, "e": 27284, "s": 27275, "text": "Output :" }, { "code": null, "e": 27295, "s": 27284, "text": "Python-gui" }, { "code": null, "e": 27307, "s": 27295, "text": "Python-PyQt" }, { "code": null, "e": 27314, "s": 27307, "text": "Python" }, { "code": null, "e": 27412, "s": 27314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27421, "s": 27412, "text": "Comments" }, { "code": null, "e": 27434, "s": 27421, "text": "Old Comments" }, { "code": null, "e": 27452, "s": 27434, "text": "Python Dictionary" }, { "code": null, "e": 27487, "s": 27452, "text": "Read a file line by line in Python" }, { "code": null, "e": 27509, "s": 27487, "text": "Enumerate() in Python" }, { "code": null, "e": 27541, "s": 27509, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27571, "s": 27541, "text": "Iterate over a list in Python" }, { "code": null, "e": 27613, "s": 27571, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27656, "s": 27613, "text": "Python program to convert a list to string" }, { "code": null, "e": 27682, "s": 27656, "text": "Python String | replace()" }, { "code": null, "e": 27726, "s": 27682, "text": "Reading and Writing to text files in Python" } ]
MongoDB query to set user defined variable into query?
For user-defined variables, use var keyword in MongoDB. Let us create a collection with documents − > db.demo327.insertOne({"FirstName":"Chris","LastName":"Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516952f8647eb59e562076") } > db.demo327.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e51695af8647eb59e562077") } > db.demo327.insertOne({"FirstName":"John","LastName":"Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516962f8647eb59e562078") } > db.demo327.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e516968f8647eb59e562079") } Display all documents from a collection with the help of find() method − > db.demo327.find(); This will produce the following output − { "_id" : ObjectId("5e516952f8647eb59e562076"), "FirstName" : "Chris", "LastName" : "Brown" } { "_id" : ObjectId("5e51695af8647eb59e562077"), "FirstName" : "David", "LastName" : "Miller" } { "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" } Following is how to set a user-defined variable into the query − > var name="John"; > db.demo327.find({"FirstName":name}); This will produce the following output − { "_id" : ObjectId("5e516962f8647eb59e562078"), "FirstName" : "John", "LastName" : "Doe" } { "_id" : ObjectId("5e516968f8647eb59e562079"), "FirstName" : "John", "LastName" : "Smith" }
[ { "code": null, "e": 1162, "s": 1062, "text": "For user-defined variables, use var keyword in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1763, "s": 1162, "text": "> db.demo327.insertOne({\"FirstName\":\"Chris\",\"LastName\":\"Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516952f8647eb59e562076\")\n}\n> db.demo327.insertOne({\"FirstName\":\"David\",\"LastName\":\"Miller\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e51695af8647eb59e562077\")\n}\n> db.demo327.insertOne({\"FirstName\":\"John\",\"LastName\":\"Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516962f8647eb59e562078\")\n}\n> db.demo327.insertOne({\"FirstName\":\"John\",\"LastName\":\"Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e516968f8647eb59e562079\")\n}" }, { "code": null, "e": 1836, "s": 1763, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1857, "s": 1836, "text": "> db.demo327.find();" }, { "code": null, "e": 1898, "s": 1857, "text": "This will produce the following output −" }, { "code": null, "e": 2271, "s": 1898, "text": "{ \"_id\" : ObjectId(\"5e516952f8647eb59e562076\"), \"FirstName\" : \"Chris\", \"LastName\" : \"Brown\" }\n{ \"_id\" : ObjectId(\"5e51695af8647eb59e562077\"), \"FirstName\" : \"David\", \"LastName\" : \"Miller\" }\n{ \"_id\" : ObjectId(\"5e516962f8647eb59e562078\"), \"FirstName\" : \"John\", \"LastName\" : \"Doe\" }\n{ \"_id\" : ObjectId(\"5e516968f8647eb59e562079\"), \"FirstName\" : \"John\", \"LastName\" : \"Smith\" }" }, { "code": null, "e": 2336, "s": 2271, "text": "Following is how to set a user-defined variable into the query −" }, { "code": null, "e": 2394, "s": 2336, "text": "> var name=\"John\";\n> db.demo327.find({\"FirstName\":name});" }, { "code": null, "e": 2435, "s": 2394, "text": "This will produce the following output −" }, { "code": null, "e": 2619, "s": 2435, "text": "{ \"_id\" : ObjectId(\"5e516962f8647eb59e562078\"), \"FirstName\" : \"John\", \"LastName\" : \"Doe\" }\n{ \"_id\" : ObjectId(\"5e516968f8647eb59e562079\"), \"FirstName\" : \"John\", \"LastName\" : \"Smith\" }" } ]
C# Trim() Method
The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed. public string Trim (); public string Trim (params char[] trimChars); Above, the trimChars parameter is an array of Unicode characters to remove, or null. Live Demo using System; using System.Globalization; public class Demo { public static void Main(String[] args) { string str1 = " JackSparrow!"; string str2 = " @#$PQRSTUV!"; Console.WriteLine("String1 = "+str1); Console.WriteLine("String1 (after trim) = "+str1.Trim()); Console.WriteLine("String1 ToUpper = "+str1.ToUpper(new CultureInfo("en-US", false))); Console.WriteLine("String1 Substring from index4 = " + str1.Substring(2, 2)); Console.WriteLine("\n\nString2 = "+str2); Console.WriteLine("String2 ToUpper = "+str2.ToUpper(new CultureInfo("en-US", false))); Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5)); } } String1 = JackSparrow! String1 (after trim) = JackSparrow! String1 ToUpper = JACKSPARROW! String1 Substring from index4 = String2 = @#$PQRSTUV! String2 ToUpper = @#$PQRSTUV! String2 Substring from index2 = @ Live Demo using System; public class Demo { public static void Main(String[] args) { string str = "JackSparrow!"; char[] arr = { 'J', 'a'}; Console.WriteLine("String = "+str); Console.WriteLine("String (after trim) = " + str.Trim(arr)); } } String = JackSparrow! String (after trim) = ckSparrow!
[ { "code": null, "e": 1233, "s": 1062, "text": "The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed." }, { "code": null, "e": 1302, "s": 1233, "text": "public string Trim ();\npublic string Trim (params char[] trimChars);" }, { "code": null, "e": 1387, "s": 1302, "text": "Above, the trimChars parameter is an array of Unicode characters to remove, or null." }, { "code": null, "e": 1398, "s": 1387, "text": " Live Demo" }, { "code": null, "e": 2094, "s": 1398, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \" JackSparrow!\";\n string str2 = \" @#$PQRSTUV!\";\n Console.WriteLine(\"String1 = \"+str1);\n Console.WriteLine(\"String1 (after trim) = \"+str1.Trim());\n Console.WriteLine(\"String1 ToUpper = \"+str1.ToUpper(new CultureInfo(\"en-US\", false)));\n Console.WriteLine(\"String1 Substring from index4 = \" + str1.Substring(2, 2));\n Console.WriteLine(\"\\n\\nString2 = \"+str2);\n Console.WriteLine(\"String2 ToUpper = \"+str2.ToUpper(new CultureInfo(\"en-US\", false)));\n Console.WriteLine(\"String2 Substring from index2 = \" + str2.Substring(0, 5));\n }\n}" }, { "code": null, "e": 2333, "s": 2094, "text": "String1 = JackSparrow!\nString1 (after trim) = JackSparrow!\nString1 ToUpper = JACKSPARROW!\nString1 Substring from index4 = \n\nString2 = @#$PQRSTUV!\nString2 ToUpper = @#$PQRSTUV!\nString2 Substring from index2 = @" }, { "code": null, "e": 2344, "s": 2333, "text": " Live Demo" }, { "code": null, "e": 2605, "s": 2344, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str = \"JackSparrow!\";\n char[] arr = { 'J', 'a'};\n Console.WriteLine(\"String = \"+str);\n Console.WriteLine(\"String (after trim) = \" + str.Trim(arr));\n }\n}" }, { "code": null, "e": 2660, "s": 2605, "text": "String = JackSparrow!\nString (after trim) = ckSparrow!" } ]
Annotate Multiple Lines of Text to ggplot2 Plot in R - GeeksforGeeks
17 Jun, 2021 In this article, we will see how to annotate Multiple Lines of text to ggplot2 Plot in R programming language. Let us first create a regular plot so that the difference is apparent, Example: R # Load Packagelibrary("ggplot2") # Create a DataFrame DF <- data.frame(X = runif(100, min=0, max=100), Y = runif(100, min=0, max=100)) # Create a ScatterPlot using ggplot2.ggplot(DF,aes(X, Y))+ geom_point(size = 5, fill = "green", color = "black", shape = 21) Output: ScatterPlot using ggplot2 Now to annotate multiple lines to the plot annotate() function is used along the regular plot. This function is passed the required value and attributes. The approach is similar to adding a single line to the plot, only difference being each new line should be created by using “\n” within the text that is to be passed to the the plot. Syntax : annotate(geom, x, y, label) Parameters : geom : We assign geom that we want to add to the plot as a first parameter which will written in “” . geom can be anything like rect, segment, pointrange etc. here we will use text as a geom as we want to add text. all other arguments will be depends on geom that we select. So here all other parameters that we will use are only works for Annotating text to plot. x : Represents the Co-ordinates of X Axis. y : Represents the Co-ordinates of Y Axis. label : Text that we want to annotate on plot. Above threes parameters (i.e x, y and label) are necessary for annotating text but here we will also use two parameters size and color which are used to represent size and color of text respectively and they are not necessary to use. Return : Geoms on plot. Example: R # Load ggplot2 Packagelibrary("ggplot2") # Create a DataFrame for PlottingDF <- data.frame(X = runif(100, min=0, max=100), Y = runif(100, min=0, max=100)) # ScatterPlot with Multiple Lines Text on it.ggplot(DF,aes(X, Y))+ geom_point(size = 5, fill = "green", color = "black", shape = 21)+ annotate("text", x = 50, y = 10, label = "Geeks For Geeks\n(R Tutorial)", size = 10, color = "dark green") Output: ScatterPlot with Annotating Multiple Lines on Plot Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24963, "s": 24851, "text": "In this article, we will see how to annotate Multiple Lines of text to ggplot2 Plot in R programming language. " }, { "code": null, "e": 25034, "s": 24963, "text": "Let us first create a regular plot so that the difference is apparent," }, { "code": null, "e": 25043, "s": 25034, "text": "Example:" }, { "code": null, "e": 25045, "s": 25043, "text": "R" }, { "code": "# Load Packagelibrary(\"ggplot2\") # Create a DataFrame DF <- data.frame(X = runif(100, min=0, max=100), Y = runif(100, min=0, max=100)) # Create a ScatterPlot using ggplot2.ggplot(DF,aes(X, Y))+ geom_point(size = 5, fill = \"green\", color = \"black\", shape = 21)", "e": 25348, "s": 25045, "text": null }, { "code": null, "e": 25356, "s": 25348, "text": "Output:" }, { "code": null, "e": 25382, "s": 25356, "text": "ScatterPlot using ggplot2" }, { "code": null, "e": 25719, "s": 25382, "text": "Now to annotate multiple lines to the plot annotate() function is used along the regular plot. This function is passed the required value and attributes. The approach is similar to adding a single line to the plot, only difference being each new line should be created by using “\\n” within the text that is to be passed to the the plot." }, { "code": null, "e": 25756, "s": 25719, "text": "Syntax : annotate(geom, x, y, label)" }, { "code": null, "e": 25769, "s": 25756, "text": "Parameters :" }, { "code": null, "e": 26134, "s": 25769, "text": "geom : We assign geom that we want to add to the plot as a first parameter which will written in “” . geom can be anything like rect, segment, pointrange etc. here we will use text as a geom as we want to add text. all other arguments will be depends on geom that we select. So here all other parameters that we will use are only works for Annotating text to plot." }, { "code": null, "e": 26177, "s": 26134, "text": "x : Represents the Co-ordinates of X Axis." }, { "code": null, "e": 26220, "s": 26177, "text": "y : Represents the Co-ordinates of Y Axis." }, { "code": null, "e": 26267, "s": 26220, "text": "label : Text that we want to annotate on plot." }, { "code": null, "e": 26501, "s": 26267, "text": "Above threes parameters (i.e x, y and label) are necessary for annotating text but here we will also use two parameters size and color which are used to represent size and color of text respectively and they are not necessary to use." }, { "code": null, "e": 26525, "s": 26501, "text": "Return : Geoms on plot." }, { "code": null, "e": 26534, "s": 26525, "text": "Example:" }, { "code": null, "e": 26536, "s": 26534, "text": "R" }, { "code": "# Load ggplot2 Packagelibrary(\"ggplot2\") # Create a DataFrame for PlottingDF <- data.frame(X = runif(100, min=0, max=100), Y = runif(100, min=0, max=100)) # ScatterPlot with Multiple Lines Text on it.ggplot(DF,aes(X, Y))+ geom_point(size = 5, fill = \"green\", color = \"black\", shape = 21)+ annotate(\"text\", x = 50, y = 10, label = \"Geeks For Geeks\\n(R Tutorial)\", size = 10, color = \"dark green\")", "e": 26987, "s": 26536, "text": null }, { "code": null, "e": 26995, "s": 26987, "text": "Output:" }, { "code": null, "e": 27046, "s": 26995, "text": "ScatterPlot with Annotating Multiple Lines on Plot" }, { "code": null, "e": 27053, "s": 27046, "text": "Picked" }, { "code": null, "e": 27062, "s": 27053, "text": "R-ggplot" }, { "code": null, "e": 27073, "s": 27062, "text": "R Language" }, { "code": null, "e": 27171, "s": 27073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27180, "s": 27171, "text": "Comments" }, { "code": null, "e": 27193, "s": 27180, "text": "Old Comments" }, { "code": null, "e": 27245, "s": 27193, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27283, "s": 27245, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27318, "s": 27283, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27376, "s": 27318, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27425, "s": 27376, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27468, "s": 27425, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27518, "s": 27468, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27535, "s": 27518, "text": "R - if statement" }, { "code": null, "e": 27572, "s": 27535, "text": "How to import an Excel File into R ?" } ]
How to retrieve all the documents from a MongoDB collection using Java?
You can retrieve documents from an existing collection in MongoDB using the find() method. db.coll.find() Where, db is the database. db is the database. coll is the collection (name) in which you want to insert the document coll is the collection (name) in which you want to insert the document Assume we have a collection named students in the MongoDB database with the following documents − {name:"Ram", age:26, city:"Mumbai"} {name:"Roja", age:28, city:"Hyderabad"} {name:"Ramani", age:35, city:"Delhi"} The following query retrieves all the documents from the collected sample. > use myDatabase() switched to db myDatabase() > db.createCollection(sample) { "ok" : 1 } > > db.sample.find() { "_id" : ObjectId("5e870492af638d501865015f"), "name" : "Ram", "age" : 26, "city" : "Mumbai" } { "_id" : ObjectId("5e870492af638d5018650160"), "name" : "Roja", "age" : 28, "city" : "Hyderabad" } { "_id" : ObjectId("5e870492af638d5018650161"), "name" : "Ramani", "age" : 35, "city" : "Delhi" } > In Java, you can retrieve all the documents in the current collection using the find() method of the com.mongodb.client.MongoCollection interface. This method returns an iterable object containing all the documents. Therefore to create a collection in MongoDB using Java program − Make sure you have installed MongoDB in your system Make sure you have installed MongoDB in your system Add the following dependency to its pom.xml file of your Java project. Add the following dependency to its pom.xml file of your Java project. <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency> Create a MongoDB client by instantiating the MongoClient class. Create a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method. import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; public class RetrievingAllDocuments { public static void main( String args[] ) { //Creating a MongoDB client MongoClient mongo = new MongoClient( "localhost" , 27017 ); //Connecting to the database MongoDatabase database = mongo.getDatabase("myDatabase"); //Creating a collection object MongoCollection<Document> collection = database.getCollection("students"); //Retrieving the documents FindIterable<Document> iterDoc = collection.find(); Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } Document{{_id=5e86db7012e9ad337c3aaef5, name=Ram, age=26, city=Hyderabad}} Document{{_id=5e86db7012e9ad337c3aaef6, name=Robert, age=27, city=Vishakhapatnam}} Document{{_id=5e86db7012e9ad337c3aaef7, name=Rahim, age=30, city=Delhi}}
[ { "code": null, "e": 1153, "s": 1062, "text": "You can retrieve documents from an existing collection in MongoDB using the find() method." }, { "code": null, "e": 1168, "s": 1153, "text": "db.coll.find()" }, { "code": null, "e": 1175, "s": 1168, "text": "Where," }, { "code": null, "e": 1195, "s": 1175, "text": "db is the database." }, { "code": null, "e": 1215, "s": 1195, "text": "db is the database." }, { "code": null, "e": 1286, "s": 1215, "text": "coll is the collection (name) in which you want to insert the document" }, { "code": null, "e": 1357, "s": 1286, "text": "coll is the collection (name) in which you want to insert the document" }, { "code": null, "e": 1455, "s": 1357, "text": "Assume we have a collection named students in the MongoDB database with the following documents −" }, { "code": null, "e": 1569, "s": 1455, "text": "{name:\"Ram\", age:26, city:\"Mumbai\"}\n{name:\"Roja\", age:28, city:\"Hyderabad\"}\n{name:\"Ramani\", age:35, city:\"Delhi\"}" }, { "code": null, "e": 1644, "s": 1569, "text": "The following query retrieves all the documents from the collected sample." }, { "code": null, "e": 2051, "s": 1644, "text": "> use myDatabase()\nswitched to db myDatabase()\n> db.createCollection(sample)\n{ \"ok\" : 1 }\n> > db.sample.find()\n{ \"_id\" : ObjectId(\"5e870492af638d501865015f\"), \"name\" : \"Ram\", \"age\" : 26, \"city\"\n: \"Mumbai\" }\n{ \"_id\" : ObjectId(\"5e870492af638d5018650160\"), \"name\" : \"Roja\", \"age\" : 28,\n\"city\" : \"Hyderabad\" }\n{ \"_id\" : ObjectId(\"5e870492af638d5018650161\"), \"name\" : \"Ramani\", \"age\" : 35,\n\"city\" : \"Delhi\" }\n>" }, { "code": null, "e": 2267, "s": 2051, "text": "In Java, you can retrieve all the documents in the current collection using the find() method of the com.mongodb.client.MongoCollection interface. This method returns an iterable object containing all the documents." }, { "code": null, "e": 2332, "s": 2267, "text": "Therefore to create a collection in MongoDB using Java program −" }, { "code": null, "e": 2384, "s": 2332, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 2436, "s": 2384, "text": "Make sure you have installed MongoDB in your system" }, { "code": null, "e": 2507, "s": 2436, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2578, "s": 2507, "text": "Add the following dependency to its pom.xml file of your Java project." }, { "code": null, "e": 2714, "s": 2578, "text": "<dependency>\n <groupId>org.mongodb</groupId>\n <artifactId>mongo-java-driver</artifactId>\n <version>3.12.2</version>\n</dependency>" }, { "code": null, "e": 2778, "s": 2714, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2842, "s": 2778, "text": "Create a MongoDB client by instantiating the MongoClient class." }, { "code": null, "e": 2896, "s": 2842, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 2950, "s": 2896, "text": "Connect to a database using the getDatabase() method." }, { "code": null, "e": 3064, "s": 2950, "text": "Get the object of the collection from which you want to retrieve the documents, using the getCollection() method." }, { "code": null, "e": 3178, "s": 3064, "text": "Get the object of the collection from which you want to retrieve the documents, using the getCollection() method." }, { "code": null, "e": 3293, "s": 3178, "text": "Retrieve the iterable object containing all the documents of the current collection by invoking the find() method." }, { "code": null, "e": 3408, "s": 3293, "text": "Retrieve the iterable object containing all the documents of the current collection by invoking the find() method." }, { "code": null, "e": 4233, "s": 3408, "text": "import com.mongodb.client.FindIterable;\nimport com.mongodb.client.MongoCollection;\nimport com.mongodb.client.MongoDatabase;\nimport java.util.Iterator;\nimport org.bson.Document;\nimport com.mongodb.MongoClient;\npublic class RetrievingAllDocuments {\n public static void main( String args[] ) {\n //Creating a MongoDB client\n MongoClient mongo = new MongoClient( \"localhost\" , 27017 );\n //Connecting to the database\n MongoDatabase database = mongo.getDatabase(\"myDatabase\");\n //Creating a collection object\n MongoCollection<Document> collection = database.getCollection(\"students\");\n //Retrieving the documents\n FindIterable<Document> iterDoc = collection.find();\n Iterator it = iterDoc.iterator();\n while (it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}" }, { "code": null, "e": 4464, "s": 4233, "text": "Document{{_id=5e86db7012e9ad337c3aaef5, name=Ram, age=26, city=Hyderabad}}\nDocument{{_id=5e86db7012e9ad337c3aaef6, name=Robert, age=27, city=Vishakhapatnam}}\nDocument{{_id=5e86db7012e9ad337c3aaef7, name=Rahim, age=30, city=Delhi}}" } ]
Print all the cycles in an undirected graph - GeeksforGeeks
02 Jul, 2021 Given an undirected graph, print all the vertices that form cycles in it. Pre-requisite: Detect Cycle in a directed graph using colors In the above diagram, the cycles have been marked with dark green color. The output for the above will be 1st cycle: 3 5 4 6 2nd cycle: 11 12 13 Approach: Using the graph coloring method, mark all the vertex of the different cycles with unique numbers. Once the graph traversal is completed, push all the similar marked numbers to an adjacency list and print the adjacency list accordingly. Given below is the algorithm: Insert the edges into an adjacency list. Call the DFS function which uses the coloring method to mark the vertex. Whenever there is a partially visited vertex, backtrack till the current vertex is reached and mark all of them with cycle numbers. Once all the vertexes are marked, increase the cycle number. Once Dfs is completed, iterate for the edges and push the same marked number edges to another adjacency list. Iterate in another adjacency list and print the vertex cycle-number wise. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print all the cycles// in an undirected graph#include <bits/stdc++.h>using namespace std;const int N = 100000; // variables to be used// in both functionsvector<int> graph[N];vector<int> cycles[N]; // Function to mark the vertex with// different colors for different cyclesvoid dfs_cycle(int u, int p, int color[], int mark[], int par[], int& cyclenumber){ // already (completely) visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not completely visited -> cycle detected. // backtrack based on parents to find the complete cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which are // in the current cycle thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for (int v : graph[u]) { // if it has not been visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par, cyclenumber); } // completely visited. color[u] = 2;} // add the edges to the graphvoid addEdge(int u, int v){ graph[u].push_back(v); graph[v].push_back(u);} // Function to print the cyclesvoid printCycles(int edges, int mark[], int& cyclenumber){ // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle cout << "Cycle Number " << i << ": "; for (int x : cycles[i]) cout << x << " "; cout << endl; }} // Driver Codeint main(){ // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color the // graph, store the parent of node int color[N]; int par[N]; // mark with unique numbers int mark[N]; // store the numbers of cycle int cyclenumber = 0; int edges = 13; // call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par, cyclenumber); // function to print the cycles printCycles(edges, mark, cyclenumber);} // Java program to print all the cycles// in an undirected graphimport java.util.*; class GFG{ static final int N = 100000; // variables to be used // in both functions @SuppressWarnings("unchecked") static Vector<Integer>[] graph = new Vector[N]; @SuppressWarnings("unchecked") static Vector<Integer>[] cycles = new Vector[N]; static int cyclenumber; // Function to mark the vertex with // different colors for different cycles static void dfs_cycle(int u, int p, int[] color, int[] mark, int[] par) { // already (completely) visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not completely visited -> cycle detected. // backtrack based on parents to find the complete cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which are // in the current cycle thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for (int v : graph[u]) { // if it has not been visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2; } // add the edges to the graph static void addEdge(int u, int v) { graph[u].add(v); graph[v].add(u); } // Function to print the cycles static void printCycles(int edges, int mark[]) { // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].add(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle System.out.printf("Cycle Number %d: ", i); for (int x : cycles[i]) System.out.printf("%d ", x); System.out.println(); } } // Driver Code public static void main(String[] args) { for (int i = 0; i < N; i++) { graph[i] = new Vector<>(); cycles[i] = new Vector<>(); } // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color the // graph, store the parent of node int[] color = new int[N]; int[] par = new int[N]; // mark with unique numbers int[] mark = new int[N]; // store the numbers of cycle cyclenumber = 0; int edges = 13; // call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par); // function to print the cycles printCycles(edges, mark); }} // This code is contributed by// sanjeev2552 # Python3 program to print all the cycles# in an undirected graphN = 100000 # variables to be used# in both functionsgraph = [[] for i in range(N)]cycles = [[] for i in range(N)] # Function to mark the vertex with# different colors for different cyclesdef dfs_cycle(u, p, color: list, mark: list, par: list): global cyclenumber # already (completely) visited vertex. if color[u] == 2: return # seen vertex, but was not # completely visited -> cycle detected. # backtrack based on parents to # find the complete cycle. if color[u] == 1: cyclenumber += 1 cur = p mark[cur] = cyclenumber # backtrack the vertex which are # in the current cycle thats found while cur != u: cur = par[cur] mark[cur] = cyclenumber return par[u] = p # partially visited. color[u] = 1 # simple dfs on graph for v in graph[u]: # if it has not been visited previously if v == par[u]: continue dfs_cycle(v, u, color, mark, par) # completely visited. color[u] = 2 # add the edges to the graphdef addEdge(u, v): graph[u].append(v) graph[v].append(u) # Function to print the cyclesdef printCycles(edges, mark: list): # push the edges that into the # cycle adjacency list for i in range(1, edges + 1): if mark[i] != 0: cycles[mark[i]].append(i) # print all the vertex with same cycle for i in range(1, cyclenumber + 1): # Print the i-th cycle print("Cycle Number %d:" % i, end = " ") for x in cycles[i]: print(x, end = " ") print() # Driver Codeif __name__ == "__main__": # add edges addEdge(1, 2) addEdge(2, 3) addEdge(3, 4) addEdge(4, 6) addEdge(4, 7) addEdge(5, 6) addEdge(3, 5) addEdge(7, 8) addEdge(6, 10) addEdge(5, 9) addEdge(10, 11) addEdge(11, 12) addEdge(11, 13) addEdge(12, 13) # arrays required to color the # graph, store the parent of node color = [0] * N par = [0] * N # mark with unique numbers mark = [0] * N # store the numbers of cycle cyclenumber = 0 edges = 13 # call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par) # function to print the cycles printCycles(edges, mark) # This code is contributed by# sanjeev2552 // C# program to print all// the cycles in an undirected// graphusing System;using System.Collections.Generic;class GFG{ static readonly int N = 100000; // variables to be used// in both functionsstatic List<int>[] graph = new List<int>[N];static List<int>[] cycles = new List<int>[N];static int cyclenumber; // Function to mark the vertex with// different colors for different cyclesstatic void dfs_cycle(int u, int p, int[] color, int[] mark, int[] par){ // already (completely) // visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not // completely visited -> cycle // detected. backtrack based on // parents to find the complete // cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which // are in the current cycle // thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph foreach (int v in graph[u]) { // if it has not been // visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2;} // add the edges to the// graphstatic void addEdge(int u, int v){ graph[u].Add(v); graph[v].Add(u);} // Function to print the cyclesstatic void printCycles(int edges, int []mark){ // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].Add(i); } // print all the vertex with // same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle Console.Write("Cycle Number " + i + ":"); foreach (int x in cycles[i]) Console.Write(" " + x); Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ for (int i = 0; i < N; i++) { graph[i] = new List<int>(); cycles[i] = new List<int>(); } // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color // the graph, store the parent // of node int[] color = new int[N]; int[] par = new int[N]; // mark with unique numbers int[] mark = new int[N]; // store the numbers of cycle cyclenumber = 0; int edges = 13; // call DFS to mark // the cycles dfs_cycle(1, 0, color, mark, par); // function to print the cycles printCycles(edges, mark);}} // This code is contributed by Amit Katiyar <script> // JavaScript program to print all// the cycles in an undirected// graph var N = 100000; // variables to be used// in both functionsvar graph = Array.from(Array(N), ()=>Array()); var cycles = Array.from(Array(N), ()=>Array()); var cyclenumber = 0; // Function to mark the vertex with// different colors for different cyclesfunction dfs_cycle(u, p, color, mark, par){ // already (completely) // visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not // completely visited -> cycle // detected. backtrack based on // parents to find the complete // cycle. if (color[u] == 1) { cyclenumber++; var cur = p; mark[cur] = cyclenumber; // backtrack the vertex which // are in the current cycle // thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for(var v of graph[u]) { // if it has not been // visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2;} // add the edges to the// graphfunction addEdge(u, v){ graph[u].push(v); graph[v].push(u);} // Function to print the cyclesfunction printCycles(edges, mark){ // push the edges that into the // cycle adjacency list for (var i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push(i); } // print all the vertex with // same cycle for (var i = 1; i <= cyclenumber; i++) { // Print the i-th cycle document.write("Cycle Number " + i + ":"); for(var x of cycles[i]) document.write(" " + x); document.write("<br>"); }} // Driver Code// add edgesaddEdge(1, 2);addEdge(2, 3);addEdge(3, 4);addEdge(4, 6);addEdge(4, 7);addEdge(5, 6);addEdge(3, 5);addEdge(7, 8);addEdge(6, 10);addEdge(5, 9);addEdge(10, 11);addEdge(11, 12);addEdge(11, 13);addEdge(12, 13);// arrays required to color// the graph, store the parent// of nodevar color = Array(N).fill(0);var par = Array(N).fill(0);// mark with unique numbersvar mark = Array(N).fill(0);// store the numbers of cyclecyclenumber = 0;var edges = 13;// call DFS to mark// the cyclesdfs_cycle(1, 0, color, mark, par);// function to print the cyclesprintCycles(edges, mark); </script> Output: Cycle Number 1: 3 4 5 6 Cycle Number 2: 11 12 13 Time Complexity: O(N + M), where N is the number of vertexes and M is the number of edges. Auxiliary Space: O(N + M) sanjeev2552 amit143katiyar rrrtnx Algorithms-Backtracking DFS Graph Coloring graph-cycle Graph DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Topological Sorting Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Ford-Fulkerson Algorithm for Maximum Flow Problem Strongly Connected Components Traveling Salesman Problem (TSP) Implementation Find the number of islands | Set 1 (Using DFS) m Coloring Problem | Backtracking-5 Hamiltonian Cycle | Backtracking-6
[ { "code": null, "e": 26439, "s": 26411, "text": "\n02 Jul, 2021" }, { "code": null, "e": 26576, "s": 26439, "text": "Given an undirected graph, print all the vertices that form cycles in it. Pre-requisite: Detect Cycle in a directed graph using colors " }, { "code": null, "e": 26684, "s": 26576, "text": "In the above diagram, the cycles have been marked with dark green color. The output for the above will be " }, { "code": null, "e": 26723, "s": 26684, "text": "1st cycle: 3 5 4 6 2nd cycle: 11 12 13" }, { "code": null, "e": 27001, "s": 26723, "text": "Approach: Using the graph coloring method, mark all the vertex of the different cycles with unique numbers. Once the graph traversal is completed, push all the similar marked numbers to an adjacency list and print the adjacency list accordingly. Given below is the algorithm: " }, { "code": null, "e": 27042, "s": 27001, "text": "Insert the edges into an adjacency list." }, { "code": null, "e": 27115, "s": 27042, "text": "Call the DFS function which uses the coloring method to mark the vertex." }, { "code": null, "e": 27308, "s": 27115, "text": "Whenever there is a partially visited vertex, backtrack till the current vertex is reached and mark all of them with cycle numbers. Once all the vertexes are marked, increase the cycle number." }, { "code": null, "e": 27418, "s": 27308, "text": "Once Dfs is completed, iterate for the edges and push the same marked number edges to another adjacency list." }, { "code": null, "e": 27492, "s": 27418, "text": "Iterate in another adjacency list and print the vertex cycle-number wise." }, { "code": null, "e": 27545, "s": 27492, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27549, "s": 27545, "text": "C++" }, { "code": null, "e": 27554, "s": 27549, "text": "Java" }, { "code": null, "e": 27562, "s": 27554, "text": "Python3" }, { "code": null, "e": 27565, "s": 27562, "text": "C#" }, { "code": null, "e": 27576, "s": 27565, "text": "Javascript" }, { "code": "// C++ program to print all the cycles// in an undirected graph#include <bits/stdc++.h>using namespace std;const int N = 100000; // variables to be used// in both functionsvector<int> graph[N];vector<int> cycles[N]; // Function to mark the vertex with// different colors for different cyclesvoid dfs_cycle(int u, int p, int color[], int mark[], int par[], int& cyclenumber){ // already (completely) visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not completely visited -> cycle detected. // backtrack based on parents to find the complete cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which are // in the current cycle thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for (int v : graph[u]) { // if it has not been visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par, cyclenumber); } // completely visited. color[u] = 2;} // add the edges to the graphvoid addEdge(int u, int v){ graph[u].push_back(v); graph[v].push_back(u);} // Function to print the cyclesvoid printCycles(int edges, int mark[], int& cyclenumber){ // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle cout << \"Cycle Number \" << i << \": \"; for (int x : cycles[i]) cout << x << \" \"; cout << endl; }} // Driver Codeint main(){ // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color the // graph, store the parent of node int color[N]; int par[N]; // mark with unique numbers int mark[N]; // store the numbers of cycle int cyclenumber = 0; int edges = 13; // call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par, cyclenumber); // function to print the cycles printCycles(edges, mark, cyclenumber);}", "e": 30132, "s": 27576, "text": null }, { "code": "// Java program to print all the cycles// in an undirected graphimport java.util.*; class GFG{ static final int N = 100000; // variables to be used // in both functions @SuppressWarnings(\"unchecked\") static Vector<Integer>[] graph = new Vector[N]; @SuppressWarnings(\"unchecked\") static Vector<Integer>[] cycles = new Vector[N]; static int cyclenumber; // Function to mark the vertex with // different colors for different cycles static void dfs_cycle(int u, int p, int[] color, int[] mark, int[] par) { // already (completely) visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not completely visited -> cycle detected. // backtrack based on parents to find the complete cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which are // in the current cycle thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for (int v : graph[u]) { // if it has not been visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2; } // add the edges to the graph static void addEdge(int u, int v) { graph[u].add(v); graph[v].add(u); } // Function to print the cycles static void printCycles(int edges, int mark[]) { // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].add(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle System.out.printf(\"Cycle Number %d: \", i); for (int x : cycles[i]) System.out.printf(\"%d \", x); System.out.println(); } } // Driver Code public static void main(String[] args) { for (int i = 0; i < N; i++) { graph[i] = new Vector<>(); cycles[i] = new Vector<>(); } // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color the // graph, store the parent of node int[] color = new int[N]; int[] par = new int[N]; // mark with unique numbers int[] mark = new int[N]; // store the numbers of cycle cyclenumber = 0; int edges = 13; // call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par); // function to print the cycles printCycles(edges, mark); }} // This code is contributed by// sanjeev2552", "e": 33472, "s": 30132, "text": null }, { "code": "# Python3 program to print all the cycles# in an undirected graphN = 100000 # variables to be used# in both functionsgraph = [[] for i in range(N)]cycles = [[] for i in range(N)] # Function to mark the vertex with# different colors for different cyclesdef dfs_cycle(u, p, color: list, mark: list, par: list): global cyclenumber # already (completely) visited vertex. if color[u] == 2: return # seen vertex, but was not # completely visited -> cycle detected. # backtrack based on parents to # find the complete cycle. if color[u] == 1: cyclenumber += 1 cur = p mark[cur] = cyclenumber # backtrack the vertex which are # in the current cycle thats found while cur != u: cur = par[cur] mark[cur] = cyclenumber return par[u] = p # partially visited. color[u] = 1 # simple dfs on graph for v in graph[u]: # if it has not been visited previously if v == par[u]: continue dfs_cycle(v, u, color, mark, par) # completely visited. color[u] = 2 # add the edges to the graphdef addEdge(u, v): graph[u].append(v) graph[v].append(u) # Function to print the cyclesdef printCycles(edges, mark: list): # push the edges that into the # cycle adjacency list for i in range(1, edges + 1): if mark[i] != 0: cycles[mark[i]].append(i) # print all the vertex with same cycle for i in range(1, cyclenumber + 1): # Print the i-th cycle print(\"Cycle Number %d:\" % i, end = \" \") for x in cycles[i]: print(x, end = \" \") print() # Driver Codeif __name__ == \"__main__\": # add edges addEdge(1, 2) addEdge(2, 3) addEdge(3, 4) addEdge(4, 6) addEdge(4, 7) addEdge(5, 6) addEdge(3, 5) addEdge(7, 8) addEdge(6, 10) addEdge(5, 9) addEdge(10, 11) addEdge(11, 12) addEdge(11, 13) addEdge(12, 13) # arrays required to color the # graph, store the parent of node color = [0] * N par = [0] * N # mark with unique numbers mark = [0] * N # store the numbers of cycle cyclenumber = 0 edges = 13 # call DFS to mark the cycles dfs_cycle(1, 0, color, mark, par) # function to print the cycles printCycles(edges, mark) # This code is contributed by# sanjeev2552", "e": 35834, "s": 33472, "text": null }, { "code": "// C# program to print all// the cycles in an undirected// graphusing System;using System.Collections.Generic;class GFG{ static readonly int N = 100000; // variables to be used// in both functionsstatic List<int>[] graph = new List<int>[N];static List<int>[] cycles = new List<int>[N];static int cyclenumber; // Function to mark the vertex with// different colors for different cyclesstatic void dfs_cycle(int u, int p, int[] color, int[] mark, int[] par){ // already (completely) // visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not // completely visited -> cycle // detected. backtrack based on // parents to find the complete // cycle. if (color[u] == 1) { cyclenumber++; int cur = p; mark[cur] = cyclenumber; // backtrack the vertex which // are in the current cycle // thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph foreach (int v in graph[u]) { // if it has not been // visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2;} // add the edges to the// graphstatic void addEdge(int u, int v){ graph[u].Add(v); graph[v].Add(u);} // Function to print the cyclesstatic void printCycles(int edges, int []mark){ // push the edges that into the // cycle adjacency list for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].Add(i); } // print all the vertex with // same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle Console.Write(\"Cycle Number \" + i + \":\"); foreach (int x in cycles[i]) Console.Write(\" \" + x); Console.WriteLine(); }} // Driver Codepublic static void Main(String[] args){ for (int i = 0; i < N; i++) { graph[i] = new List<int>(); cycles[i] = new List<int>(); } // add edges addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); // arrays required to color // the graph, store the parent // of node int[] color = new int[N]; int[] par = new int[N]; // mark with unique numbers int[] mark = new int[N]; // store the numbers of cycle cyclenumber = 0; int edges = 13; // call DFS to mark // the cycles dfs_cycle(1, 0, color, mark, par); // function to print the cycles printCycles(edges, mark);}} // This code is contributed by Amit Katiyar", "e": 38621, "s": 35834, "text": null }, { "code": "<script> // JavaScript program to print all// the cycles in an undirected// graph var N = 100000; // variables to be used// in both functionsvar graph = Array.from(Array(N), ()=>Array()); var cycles = Array.from(Array(N), ()=>Array()); var cyclenumber = 0; // Function to mark the vertex with// different colors for different cyclesfunction dfs_cycle(u, p, color, mark, par){ // already (completely) // visited vertex. if (color[u] == 2) { return; } // seen vertex, but was not // completely visited -> cycle // detected. backtrack based on // parents to find the complete // cycle. if (color[u] == 1) { cyclenumber++; var cur = p; mark[cur] = cyclenumber; // backtrack the vertex which // are in the current cycle // thats found while (cur != u) { cur = par[cur]; mark[cur] = cyclenumber; } return; } par[u] = p; // partially visited. color[u] = 1; // simple dfs on graph for(var v of graph[u]) { // if it has not been // visited previously if (v == par[u]) { continue; } dfs_cycle(v, u, color, mark, par); } // completely visited. color[u] = 2;} // add the edges to the// graphfunction addEdge(u, v){ graph[u].push(v); graph[v].push(u);} // Function to print the cyclesfunction printCycles(edges, mark){ // push the edges that into the // cycle adjacency list for (var i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push(i); } // print all the vertex with // same cycle for (var i = 1; i <= cyclenumber; i++) { // Print the i-th cycle document.write(\"Cycle Number \" + i + \":\"); for(var x of cycles[i]) document.write(\" \" + x); document.write(\"<br>\"); }} // Driver Code// add edgesaddEdge(1, 2);addEdge(2, 3);addEdge(3, 4);addEdge(4, 6);addEdge(4, 7);addEdge(5, 6);addEdge(3, 5);addEdge(7, 8);addEdge(6, 10);addEdge(5, 9);addEdge(10, 11);addEdge(11, 12);addEdge(11, 13);addEdge(12, 13);// arrays required to color// the graph, store the parent// of nodevar color = Array(N).fill(0);var par = Array(N).fill(0);// mark with unique numbersvar mark = Array(N).fill(0);// store the numbers of cyclecyclenumber = 0;var edges = 13;// call DFS to mark// the cyclesdfs_cycle(1, 0, color, mark, par);// function to print the cyclesprintCycles(edges, mark); </script>", "e": 40959, "s": 38621, "text": null }, { "code": null, "e": 40969, "s": 40959, "text": "Output: " }, { "code": null, "e": 41020, "s": 40969, "text": "Cycle Number 1: 3 4 5 6 \nCycle Number 2: 11 12 13 " }, { "code": null, "e": 41137, "s": 41020, "text": "Time Complexity: O(N + M), where N is the number of vertexes and M is the number of edges. Auxiliary Space: O(N + M)" }, { "code": null, "e": 41149, "s": 41137, "text": "sanjeev2552" }, { "code": null, "e": 41164, "s": 41149, "text": "amit143katiyar" }, { "code": null, "e": 41171, "s": 41164, "text": "rrrtnx" }, { "code": null, "e": 41195, "s": 41171, "text": "Algorithms-Backtracking" }, { "code": null, "e": 41199, "s": 41195, "text": "DFS" }, { "code": null, "e": 41214, "s": 41199, "text": "Graph Coloring" }, { "code": null, "e": 41226, "s": 41214, "text": "graph-cycle" }, { "code": null, "e": 41232, "s": 41226, "text": "Graph" }, { "code": null, "e": 41236, "s": 41232, "text": "DFS" }, { "code": null, "e": 41242, "s": 41236, "text": "Graph" }, { "code": null, "e": 41340, "s": 41242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41360, "s": 41340, "text": "Topological Sorting" }, { "code": null, "e": 41391, "s": 41360, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41424, "s": 41391, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 41492, "s": 41424, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 41542, "s": 41492, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 41572, "s": 41542, "text": "Strongly Connected Components" }, { "code": null, "e": 41620, "s": 41572, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 41667, "s": 41620, "text": "Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 41703, "s": 41667, "text": "m Coloring Problem | Backtracking-5" } ]
Count distinct in Pandas aggregation - GeeksforGeeks
03 Mar, 2021 In this article, let’s see how we can count distinct in pandas aggregation. So to count the distinct in pandas aggregation we are going to use groupby() and add() method. groupby(): This method is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. We can create a grouping of categories and apply a function to the categories. The abstract definition of grouping is to provide a mapping of labels to group names agg(): This method is used to pass a function or list of functions to be applied on a series or even each element of series separately. In the case of a list of functions, multiple results are returned by agg() method. Below are some examples which depict how to count distinct in Pandas aggregation: Example 1: Python # import moduleimport pandas as pdimport numpy as np # create Data framedf = pd.DataFrame({'Video_Upload_Date': ['2020-01-17', '2020-01-17', '2020-01-19', '2020-01-19', '2020-01-19'], 'Viewer_Id': ['031', '031', '032', '032', '032'], 'Watch_Time': [34, 43, 43, 41, 40]}) # print original Dataframeprint(df) # let's Count distinct in Pandas aggregationdf = df.groupby("Video_Upload_Date").agg( {"Watch_Time": np.sum, "Viewer_Id": pd.Series.nunique}) # print final outputprint(df) Output: Example 2: Python # import moduleimport pandas as pdimport numpy as np # create Data framedf = pd.DataFrame({'Order Date': ['2021-02-22', '2021-02-22', '2021-02-22', '2021-02-24', '2021-02-24'], 'Product Id': ['021', '021', '022', '022', '022'], 'Order Quantity': [23, 22, 22, 45, 10]}) # print original Dataframeprint(df) # let's Count distinct in Pandas aggregationdf = df.groupby("Order Date").agg({"Order Quantity": np.sum, "Product Id": pd.Series.nunique}) # print final outputprint(df) Output: Picked Python pandas-groupby 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 ? 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": 25537, "s": 25509, "text": "\n03 Mar, 2021" }, { "code": null, "e": 25710, "s": 25537, "text": "In this article, let’s see how we can count distinct in pandas aggregation. So to count the distinct in pandas aggregation we are going to use groupby() and add() method. " }, { "code": null, "e": 26009, "s": 25710, "text": "groupby(): This method is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. We can create a grouping of categories and apply a function to the categories. The abstract definition of grouping is to provide a mapping of labels to group names" }, { "code": null, "e": 26228, "s": 26009, "text": "agg(): This method is used to pass a function or list of functions to be applied on a series or even each element of series separately. In the case of a list of functions, multiple results are returned by agg() method." }, { "code": null, "e": 26310, "s": 26228, "text": "Below are some examples which depict how to count distinct in Pandas aggregation:" }, { "code": null, "e": 26321, "s": 26310, "text": "Example 1:" }, { "code": null, "e": 26328, "s": 26321, "text": "Python" }, { "code": "# import moduleimport pandas as pdimport numpy as np # create Data framedf = pd.DataFrame({'Video_Upload_Date': ['2020-01-17', '2020-01-17', '2020-01-19', '2020-01-19', '2020-01-19'], 'Viewer_Id': ['031', '031', '032', '032', '032'], 'Watch_Time': [34, 43, 43, 41, 40]}) # print original Dataframeprint(df) # let's Count distinct in Pandas aggregationdf = df.groupby(\"Video_Upload_Date\").agg( {\"Watch_Time\": np.sum, \"Viewer_Id\": pd.Series.nunique}) # print final outputprint(df)", "e": 27042, "s": 26328, "text": null }, { "code": null, "e": 27050, "s": 27042, "text": "Output:" }, { "code": null, "e": 27061, "s": 27050, "text": "Example 2:" }, { "code": null, "e": 27068, "s": 27061, "text": "Python" }, { "code": "# import moduleimport pandas as pdimport numpy as np # create Data framedf = pd.DataFrame({'Order Date': ['2021-02-22', '2021-02-22', '2021-02-22', '2021-02-24', '2021-02-24'], 'Product Id': ['021', '021', '022', '022', '022'], 'Order Quantity': [23, 22, 22, 45, 10]}) # print original Dataframeprint(df) # let's Count distinct in Pandas aggregationdf = df.groupby(\"Order Date\").agg({\"Order Quantity\": np.sum, \"Product Id\": pd.Series.nunique}) # print final outputprint(df)", "e": 27818, "s": 27068, "text": null }, { "code": null, "e": 27826, "s": 27818, "text": "Output:" }, { "code": null, "e": 27833, "s": 27826, "text": "Picked" }, { "code": null, "e": 27855, "s": 27833, "text": "Python pandas-groupby" }, { "code": null, "e": 27869, "s": 27855, "text": "Python-pandas" }, { "code": null, "e": 27876, "s": 27869, "text": "Python" }, { "code": null, "e": 27974, "s": 27876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28006, "s": 27974, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28048, "s": 28006, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28090, "s": 28048, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28117, "s": 28090, "text": "Python Classes and Objects" }, { "code": null, "e": 28173, "s": 28117, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28212, "s": 28173, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28234, "s": 28212, "text": "Defaultdict in Python" }, { "code": null, "e": 28265, "s": 28234, "text": "Python | os.path.join() method" }, { "code": null, "e": 28294, "s": 28265, "text": "Create a directory in Python" } ]
Maximum Sum Subsequence of length k - GeeksforGeeks
24 Jun, 2021 Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk. Examples: Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible sum is 9 10 21 Input : n = 9 k = 4 A=[2 5 3 9 15 33 6 18 20] Output : 62 Possible Increasing subsequence of Length 4 with maximum possible sum is 9 15 18 20 One thing that is clearly visible that it can be easily solved with dynamic programming and this problem is a simple variation of Longest Increasing Subsequence. If you are unknown of how to calculate the longest increasing subsequence then see the implementation going to the link. Naive Approach: In the brute force approach, first we will try to find all the subsequences of length k and will check whether they are increasing or not. There could be nCk such sequences in the worst case when all elements are in increasing order. Now we will find the maximum possible sum for such sequences. Time Complexity would be O((nCk)*n). Efficient Approach: We will be using a two-dimensional dp array in which dp[i][l] means that maximum sum subsequence of length l taking array values from 0 to i and the subsequence is ending at index ‘i’. Range of ‘l’ is from 0 to k-1. Using the approach of longer increasing subsequence on the inner loop when j<i we will check if arr[j] < arr[i] for checking if subsequence increasing. This problem can be divided into its subproblems: dp[i][1]=arr[i] for length 1 , maximum increasing subsequence is equal to the array value dp[i][l+1]= max(dp[i][l+1], dp[j][l]+arr[i]) for any length l between 1 to k-1 This means that if for ith position and subsequence of length l+1 , there exists some subsequence at j (j < i) of length l for which sum of dp[j][l] + arr[i] is more than its initial calculated value then update that value. Then finally we will find the maximum value of dp[i][k] i.e for every ‘i’ if subsequence of k length is causing more sum than update the required ans. Below is the implementation code: C++ Java Python3 C# Javascript /*C++ program to calculate the maximum sum ofincreasing subsequence of length k*/#include <bits/stdc++.h>using namespace std;int MaxIncreasingSub(int arr[], int n, int k){ // In the implementation dp[n][k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int dp[n][k + 1], ans = -1; // Initializing whole multidimensional // dp array with value -1 memset(dp, -1, sizeof(dp)); // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i][1] with that array value for (int i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver functionint main(){ int n = 8, k = 3; int arr[n] = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); cout << ans << "\n"; return 0;} /*Java program to calculate the maximum sum ofincreasing subsequence of length k*/import java.util.*; class GFG{ static int MaxIncreasingSub(int arr[], int n, int k){ // In the implementation dp[n][k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int dp[][]=new int[n][k + 1], ans = -1; // Initializing whole multidimensional // dp array with value -1 for(int i = 0; i < n; i++) for(int j = 0; j < k + 1; j++) dp[i][j]=-1; // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i][1] with that array value for (int i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = Math.max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver codepublic static void main(String args[]){ int n = 8, k = 3; int arr[] = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); System.out.println(ans ); }} // This code is contributed by Arnab Kundu # Python program to calculate the maximum sum# of increasing subsequence of length k def MaxIncreasingSub(arr, n, k): # In the implementation dp[n][k] represents # maximum sum subsequence of length k and the # subsequence is ending at index n. dp = [-1]*n ans = -1 # Initializing whole multidimensional # dp array with value - 1 for i in range(n): dp[i] = [-1]*(k+1) # For each ith position increasing subsequence # of length 1 is equal to that array ith value # so initializing dp[i][1] with that array value for i in range(n): dp[i][1] = arr[i] # Starting from 1st index as we have calculated # for 0th index. Computing optimized dp values # in bottom-up manner for i in range(1,n): for j in range(i): # check for increasing subsequence if arr[j] < arr[i]: for l in range(1,k): # Proceed if value is pre calculated if dp[j][l] != -1: # Check for all the subsequences # ending at any j < i and try including # element at index i in them for # some length l. Update the maximum # value for every length. dp[i][l+1] = max(dp[i][l+1], dp[j][l] + arr[i]) # The final result would be the maximum # value of dp[i][k] for all different i. for i in range(n): if ans < dp[i][k]: ans = dp[i][k] # When no subsequence of length k is # possible sum would be considered zero return (0 if ans == -1 else ans) # Driver Codeif __name__ == "__main__": n, k = 8, 3 arr = [8, 5, 9, 10, 5, 6, 21, 8] ans = MaxIncreasingSub(arr, n, k) print(ans) # This code is contributed by# sanjeev2552 /*C# program to calculate the maximum sum ofincreasing subsequence of length k*/using System; class GFG{ static int MaxIncreasingSub(int []arr, int n, int k){ // In the implementation dp[n,k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int [,]dp=new int[n, k + 1]; int ans = -1; // Initializing whole multidimensional // dp array with value -1 for(int i = 0; i < n; i++) for(int j = 0; j < k + 1; j++) dp[i, j]=-1; // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i,1] with that array value for (int i = 0; i < n; i++) { dp[i, 1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j, l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i, l + 1] = Math.Max(dp[i, l + 1], dp[j, l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i,k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i, k]) ans = dp[i, k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver codepublic static void Main(String []args){ int n = 8, k = 3; int []arr = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); Console.WriteLine(ans );}} // This code contributed by Rajput-Ji <script> // Javascript program to calculate the// maximum sum of increasing subsequence// of length kfunction MaxIncreasingSub(arr, n, k){ // In the implementation dp[n][k] // represents maximum sum subsequence // of length k and the subsequence is // ending at index n. let dp = new Array(n); for(let i = 0; i < dp.length; i++) { dp[i] = new Array(2); } let ans = -1; // Initializing whole multidimensional // dp array with value -1 for(let i = 0; i < n; i++) for(let j = 0; j < k + 1; j++) dp[i][j] = -1; // For each ith position increasing // subsequence of length 1 is equal // to that array ith value so // initializing dp[i][1] with that // array value for(let i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we // have calculated for 0th index. // Computing optimized dp values // in bottom-up manner for(let i = 1; i < n; i++) { for(let j = 0; j < i; j++) { // Check for increasing subsequence if (arr[j] < arr[i]) { for(let l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = Math.max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for(let i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return(ans == -1) ? 0 : ans;} // Driver Codelet n = 8, k = 3;let arr = [ 8, 5, 9, 10, 5, 6, 21, 8 ];let ans = MaxIncreasingSub(arr, n, k); document.write(ans); // This code is contributed by code_hunt </script> 40 Time complexity: O(n^2*k) Space complexity: O(n^2) andrew1234 Rajput-Ji sanjeev2552 code_hunt surinderdawra388 subsequence Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search 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": 26567, "s": 26539, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26727, "s": 26567, "text": "Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk." }, { "code": null, "e": 26737, "s": 26727, "text": "Examples:" }, { "code": null, "e": 26872, "s": 26737, "text": "Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible sum is 9 10 21" }, { "code": null, "e": 27016, "s": 26872, "text": "Input : n = 9 k = 4 A=[2 5 3 9 15 33 6 18 20] Output : 62 Possible Increasing subsequence of Length 4 with maximum possible sum is 9 15 18 20 " }, { "code": null, "e": 27299, "s": 27016, "text": "One thing that is clearly visible that it can be easily solved with dynamic programming and this problem is a simple variation of Longest Increasing Subsequence. If you are unknown of how to calculate the longest increasing subsequence then see the implementation going to the link." }, { "code": null, "e": 27648, "s": 27299, "text": "Naive Approach: In the brute force approach, first we will try to find all the subsequences of length k and will check whether they are increasing or not. There could be nCk such sequences in the worst case when all elements are in increasing order. Now we will find the maximum possible sum for such sequences. Time Complexity would be O((nCk)*n)." }, { "code": null, "e": 28037, "s": 27648, "text": "Efficient Approach: We will be using a two-dimensional dp array in which dp[i][l] means that maximum sum subsequence of length l taking array values from 0 to i and the subsequence is ending at index ‘i’. Range of ‘l’ is from 0 to k-1. Using the approach of longer increasing subsequence on the inner loop when j<i we will check if arr[j] < arr[i] for checking if subsequence increasing. " }, { "code": null, "e": 28088, "s": 28037, "text": "This problem can be divided into its subproblems: " }, { "code": null, "e": 28259, "s": 28088, "text": "dp[i][1]=arr[i] for length 1 , maximum increasing subsequence is equal to the array value dp[i][l+1]= max(dp[i][l+1], dp[j][l]+arr[i]) for any length l between 1 to k-1 " }, { "code": null, "e": 28634, "s": 28259, "text": "This means that if for ith position and subsequence of length l+1 , there exists some subsequence at j (j < i) of length l for which sum of dp[j][l] + arr[i] is more than its initial calculated value then update that value. Then finally we will find the maximum value of dp[i][k] i.e for every ‘i’ if subsequence of k length is causing more sum than update the required ans." }, { "code": null, "e": 28670, "s": 28634, "text": "Below is the implementation code: " }, { "code": null, "e": 28674, "s": 28670, "text": "C++" }, { "code": null, "e": 28679, "s": 28674, "text": "Java" }, { "code": null, "e": 28687, "s": 28679, "text": "Python3" }, { "code": null, "e": 28690, "s": 28687, "text": "C#" }, { "code": null, "e": 28701, "s": 28690, "text": "Javascript" }, { "code": "/*C++ program to calculate the maximum sum ofincreasing subsequence of length k*/#include <bits/stdc++.h>using namespace std;int MaxIncreasingSub(int arr[], int n, int k){ // In the implementation dp[n][k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int dp[n][k + 1], ans = -1; // Initializing whole multidimensional // dp array with value -1 memset(dp, -1, sizeof(dp)); // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i][1] with that array value for (int i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver functionint main(){ int n = 8, k = 3; int arr[n] = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); cout << ans << \"\\n\"; return 0;}", "e": 30744, "s": 28701, "text": null }, { "code": "/*Java program to calculate the maximum sum ofincreasing subsequence of length k*/import java.util.*; class GFG{ static int MaxIncreasingSub(int arr[], int n, int k){ // In the implementation dp[n][k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int dp[][]=new int[n][k + 1], ans = -1; // Initializing whole multidimensional // dp array with value -1 for(int i = 0; i < n; i++) for(int j = 0; j < k + 1; j++) dp[i][j]=-1; // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i][1] with that array value for (int i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = Math.max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver codepublic static void main(String args[]){ int n = 8, k = 3; int arr[] = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); System.out.println(ans ); }} // This code is contributed by Arnab Kundu", "e": 32987, "s": 30744, "text": null }, { "code": "# Python program to calculate the maximum sum# of increasing subsequence of length k def MaxIncreasingSub(arr, n, k): # In the implementation dp[n][k] represents # maximum sum subsequence of length k and the # subsequence is ending at index n. dp = [-1]*n ans = -1 # Initializing whole multidimensional # dp array with value - 1 for i in range(n): dp[i] = [-1]*(k+1) # For each ith position increasing subsequence # of length 1 is equal to that array ith value # so initializing dp[i][1] with that array value for i in range(n): dp[i][1] = arr[i] # Starting from 1st index as we have calculated # for 0th index. Computing optimized dp values # in bottom-up manner for i in range(1,n): for j in range(i): # check for increasing subsequence if arr[j] < arr[i]: for l in range(1,k): # Proceed if value is pre calculated if dp[j][l] != -1: # Check for all the subsequences # ending at any j < i and try including # element at index i in them for # some length l. Update the maximum # value for every length. dp[i][l+1] = max(dp[i][l+1], dp[j][l] + arr[i]) # The final result would be the maximum # value of dp[i][k] for all different i. for i in range(n): if ans < dp[i][k]: ans = dp[i][k] # When no subsequence of length k is # possible sum would be considered zero return (0 if ans == -1 else ans) # Driver Codeif __name__ == \"__main__\": n, k = 8, 3 arr = [8, 5, 9, 10, 5, 6, 21, 8] ans = MaxIncreasingSub(arr, n, k) print(ans) # This code is contributed by# sanjeev2552", "e": 34887, "s": 32987, "text": null }, { "code": "/*C# program to calculate the maximum sum ofincreasing subsequence of length k*/using System; class GFG{ static int MaxIncreasingSub(int []arr, int n, int k){ // In the implementation dp[n,k] represents // maximum sum subsequence of length k and the // subsequence is ending at index n. int [,]dp=new int[n, k + 1]; int ans = -1; // Initializing whole multidimensional // dp array with value -1 for(int i = 0; i < n; i++) for(int j = 0; j < k + 1; j++) dp[i, j]=-1; // For each ith position increasing subsequence // of length 1 is equal to that array ith value // so initializing dp[i,1] with that array value for (int i = 0; i < n; i++) { dp[i, 1] = arr[i]; } // Starting from 1st index as we have calculated // for 0th index. Computing optimized dp values // in bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // check for increasing subsequence if (arr[j] < arr[i]) { for (int l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j, l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i, l + 1] = Math.Max(dp[i, l + 1], dp[j, l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i,k] for all different i. for (int i = 0; i < n; i++) { if (ans < dp[i, k]) ans = dp[i, k]; } // When no subsequence of length k is // possible sum would be considered zero return (ans == -1) ? 0 : ans;} // Driver codepublic static void Main(String []args){ int n = 8, k = 3; int []arr = { 8, 5, 9, 10, 5, 6, 21, 8 }; int ans = MaxIncreasingSub(arr, n, k); Console.WriteLine(ans );}} // This code contributed by Rajput-Ji", "e": 37114, "s": 34887, "text": null }, { "code": "<script> // Javascript program to calculate the// maximum sum of increasing subsequence// of length kfunction MaxIncreasingSub(arr, n, k){ // In the implementation dp[n][k] // represents maximum sum subsequence // of length k and the subsequence is // ending at index n. let dp = new Array(n); for(let i = 0; i < dp.length; i++) { dp[i] = new Array(2); } let ans = -1; // Initializing whole multidimensional // dp array with value -1 for(let i = 0; i < n; i++) for(let j = 0; j < k + 1; j++) dp[i][j] = -1; // For each ith position increasing // subsequence of length 1 is equal // to that array ith value so // initializing dp[i][1] with that // array value for(let i = 0; i < n; i++) { dp[i][1] = arr[i]; } // Starting from 1st index as we // have calculated for 0th index. // Computing optimized dp values // in bottom-up manner for(let i = 1; i < n; i++) { for(let j = 0; j < i; j++) { // Check for increasing subsequence if (arr[j] < arr[i]) { for(let l = 1; l <= k - 1; l++) { // Proceed if value is pre calculated if (dp[j][l] != -1) { // Check for all the subsequences // ending at any j<i and try including // element at index i in them for // some length l. Update the maximum // value for every length. dp[i][l + 1] = Math.max(dp[i][l + 1], dp[j][l] + arr[i]); } } } } } // The final result would be the maximum // value of dp[i][k] for all different i. for(let i = 0; i < n; i++) { if (ans < dp[i][k]) ans = dp[i][k]; } // When no subsequence of length k is // possible sum would be considered zero return(ans == -1) ? 0 : ans;} // Driver Codelet n = 8, k = 3;let arr = [ 8, 5, 9, 10, 5, 6, 21, 8 ];let ans = MaxIncreasingSub(arr, n, k); document.write(ans); // This code is contributed by code_hunt </script>", "e": 39477, "s": 37114, "text": null }, { "code": null, "e": 39480, "s": 39477, "text": "40" }, { "code": null, "e": 39535, "s": 39482, "text": "Time complexity: O(n^2*k) Space complexity: O(n^2) " }, { "code": null, "e": 39546, "s": 39535, "text": "andrew1234" }, { "code": null, "e": 39556, "s": 39546, "text": "Rajput-Ji" }, { "code": null, "e": 39568, "s": 39556, "text": "sanjeev2552" }, { "code": null, "e": 39578, "s": 39568, "text": "code_hunt" }, { "code": null, "e": 39595, "s": 39578, "text": "surinderdawra388" }, { "code": null, "e": 39607, "s": 39595, "text": "subsequence" }, { "code": null, "e": 39614, "s": 39607, "text": "Arrays" }, { "code": null, "e": 39634, "s": 39614, "text": "Dynamic Programming" }, { "code": null, "e": 39641, "s": 39634, "text": "Arrays" }, { "code": null, "e": 39661, "s": 39641, "text": "Dynamic Programming" }, { "code": null, "e": 39759, "s": 39661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39803, "s": 39759, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39851, "s": 39803, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39874, "s": 39851, "text": "Introduction to Arrays" }, { "code": null, "e": 39906, "s": 39874, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39920, "s": 39906, "text": "Linear Search" }, { "code": null, "e": 39949, "s": 39920, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 39979, "s": 39949, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 40013, "s": 39979, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 40044, "s": 40013, "text": "Bellman–Ford Algorithm | DP-23" } ]
Print Binary Equivalent of an Integer using Recursion in Java - GeeksforGeeks
04 Nov, 2020 Given an integer number as input, we need to write a program to convert the given Integer number into an equivalent binary number by using JAVA. BigInteger class Is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types. Examples: Input : 1 Output: 1 Input : 12 Output: 1100 Input : 32 Output: 100000 Algorithm Keep the track of remainder when the number is divided by 2 in an array.Divide the number by 2.Repeat the above two steps until the number is greater than zero.Print the array in reverse order now. Keep the track of remainder when the number is divided by 2 in an array. Divide the number by 2. Repeat the above two steps until the number is greater than zero. Print the array in reverse order now. Step-wise Execution: Suppose the binary number is 20. Remainder, when 20 is divided by 2, is zero. Therefore, a[0] = 0. Divide 20 by 2. New number is 20/2 = 10. The remainder, when 10 is divided by 2, is zero. Therefore, a[1] = 0. Divide 10 by 2. New number is 10/2 = 5. The remainder, when 5 is divided by 2, is 1. Therefore, a[2] = 1. Divide 5 by 2. New number is 5/2 = 2. The remainder, when 2 is divided by 2, is zero. Therefore, a[3] = 0. Divide 2 by 2. New number is 2/2 = 1. The remainder, when 1 is divided by 2, is 1. Therefore, a[4] = 1. Divide 1 by 2. New number is 1/2 = 0. Since number becomes = 0. Print the array in reverse order. Therefore, the equivalent binary number is 10100. The below image shows it more clearly, the process. Below is the implementation of the above idea in JAVA. Java // Java Program to Print Binary// Equivalent of an Integer// using Recursionimport java.util.*;class GFG { public static int binaryConv(int n) { if (n == 1) { return 1; } return binaryConv(n / 2) * 10 + n % 2; } public static void main(String[] args) { int N = 20; System.out.println(binaryConv(N)); }} 10100 Time Complexity: O (log(n)) B. Conversion using BigInteger class Java // Java Program to Print Binary// Equivalent of an Integer// using Recursionimport java.util.*;import java.math.*;class GFG { public static BigInteger binaryConv(BigInteger n) { if (n.compareTo(BigInteger.valueOf(1)) == 0) { return BigInteger.valueOf(1); } return ((binaryConv(n.divide(BigInteger.valueOf(2))).multiply(BigInteger.valueOf(10))).add(n.mod(BigInteger.valueOf(2)))); } public static void main(String[] args) { BigInteger N = new BigInteger("9876543210987543210"); System.out.println(binaryConv(N)); }} 1000100100010000100001111011100011100011101101010101101010101010 Time Complexity: O (log(n)) 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. 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 Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25861, "s": 25833, "text": "\n04 Nov, 2020" }, { "code": null, "e": 26173, "s": 25861, "text": "Given an integer number as input, we need to write a program to convert the given Integer number into an equivalent binary number by using JAVA. BigInteger class Is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types." }, { "code": null, "e": 26183, "s": 26173, "text": "Examples:" }, { "code": null, "e": 26259, "s": 26183, "text": "Input : 1\nOutput: 1\n\nInput : 12\nOutput: 1100\n\nInput : 32\nOutput: 100000\n" }, { "code": null, "e": 26269, "s": 26259, "text": "Algorithm" }, { "code": null, "e": 26468, "s": 26269, "text": "Keep the track of remainder when the number is divided by 2 in an array.Divide the number by 2.Repeat the above two steps until the number is greater than zero.Print the array in reverse order now. " }, { "code": null, "e": 26541, "s": 26468, "text": "Keep the track of remainder when the number is divided by 2 in an array." }, { "code": null, "e": 26565, "s": 26541, "text": "Divide the number by 2." }, { "code": null, "e": 26631, "s": 26565, "text": "Repeat the above two steps until the number is greater than zero." }, { "code": null, "e": 26670, "s": 26631, "text": "Print the array in reverse order now. " }, { "code": null, "e": 26724, "s": 26670, "text": "Step-wise Execution: Suppose the binary number is 20." }, { "code": null, "e": 26790, "s": 26724, "text": "Remainder, when 20 is divided by 2, is zero. Therefore, a[0] = 0." }, { "code": null, "e": 26831, "s": 26790, "text": "Divide 20 by 2. New number is 20/2 = 10." }, { "code": null, "e": 26901, "s": 26831, "text": "The remainder, when 10 is divided by 2, is zero. Therefore, a[1] = 0." }, { "code": null, "e": 26941, "s": 26901, "text": "Divide 10 by 2. New number is 10/2 = 5." }, { "code": null, "e": 27007, "s": 26941, "text": "The remainder, when 5 is divided by 2, is 1. Therefore, a[2] = 1." }, { "code": null, "e": 27045, "s": 27007, "text": "Divide 5 by 2. New number is 5/2 = 2." }, { "code": null, "e": 27114, "s": 27045, "text": "The remainder, when 2 is divided by 2, is zero. Therefore, a[3] = 0." }, { "code": null, "e": 27152, "s": 27114, "text": "Divide 2 by 2. New number is 2/2 = 1." }, { "code": null, "e": 27218, "s": 27152, "text": "The remainder, when 1 is divided by 2, is 1. Therefore, a[4] = 1." }, { "code": null, "e": 27256, "s": 27218, "text": "Divide 1 by 2. New number is 1/2 = 0." }, { "code": null, "e": 27366, "s": 27256, "text": "Since number becomes = 0. Print the array in reverse order. Therefore, the equivalent binary number is 10100." }, { "code": null, "e": 27418, "s": 27366, "text": "The below image shows it more clearly, the process." }, { "code": null, "e": 27473, "s": 27418, "text": "Below is the implementation of the above idea in JAVA." }, { "code": null, "e": 27478, "s": 27473, "text": "Java" }, { "code": "// Java Program to Print Binary// Equivalent of an Integer// using Recursionimport java.util.*;class GFG { public static int binaryConv(int n) { if (n == 1) { return 1; } return binaryConv(n / 2) * 10 + n % 2; } public static void main(String[] args) { int N = 20; System.out.println(binaryConv(N)); }}", "e": 27849, "s": 27478, "text": null }, { "code": null, "e": 27857, "s": 27849, "text": "10100\n\n" }, { "code": null, "e": 27885, "s": 27857, "text": "Time Complexity: O (log(n))" }, { "code": null, "e": 27922, "s": 27885, "text": "B. Conversion using BigInteger class" }, { "code": null, "e": 27927, "s": 27922, "text": "Java" }, { "code": "// Java Program to Print Binary// Equivalent of an Integer// using Recursionimport java.util.*;import java.math.*;class GFG { public static BigInteger binaryConv(BigInteger n) { if (n.compareTo(BigInteger.valueOf(1)) == 0) { return BigInteger.valueOf(1); } return ((binaryConv(n.divide(BigInteger.valueOf(2))).multiply(BigInteger.valueOf(10))).add(n.mod(BigInteger.valueOf(2)))); } public static void main(String[] args) { BigInteger N = new BigInteger(\"9876543210987543210\"); System.out.println(binaryConv(N)); }}", "e": 28510, "s": 27927, "text": null }, { "code": null, "e": 28577, "s": 28510, "text": "1000100100010000100001111011100011100011101101010101101010101010\n\n" }, { "code": null, "e": 28605, "s": 28577, "text": "Time Complexity: O (log(n))" }, { "code": null, "e": 28629, "s": 28605, "text": "Technical Scripter 2020" }, { "code": null, "e": 28634, "s": 28629, "text": "Java" }, { "code": null, "e": 28648, "s": 28634, "text": "Java Programs" }, { "code": null, "e": 28667, "s": 28648, "text": "Technical Scripter" }, { "code": null, "e": 28672, "s": 28667, "text": "Java" }, { "code": null, "e": 28770, "s": 28672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28821, "s": 28770, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28851, "s": 28821, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28866, "s": 28851, "text": "Stream In Java" }, { "code": null, "e": 28885, "s": 28866, "text": "Interfaces in Java" }, { "code": null, "e": 28916, "s": 28885, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28944, "s": 28916, "text": "Initializing a List in Java" }, { "code": null, "e": 28988, "s": 28944, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 29014, "s": 28988, "text": "Java Programming Examples" }, { "code": null, "e": 29048, "s": 29014, "text": "Convert Double to Integer in Java" } ]
Go Keywords - GeeksforGeeks
03 Feb, 2020 Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. Example: // Go program to illustrate the// use of keywordspackage mainimport "fmt" // Here, package, import, func,// var are keywordsfunc main() { // Here, a is a valid identifiervar a = "GeeksforGeeks" fmt.Println(a) // Here, the default is an// illegal identifier and// compiler will throw an error// var default = "GFG"} Output: GeeksforGeeks There are total 25 keywords present in the Go language as follows: Example: // Go program to illustrate // the use of keywords // Here package keyword is used to // include main package in the programpackage main // import keyword is used to // import "fmt" in your packageimport "fmt" // func is used to// create functionfunc main() { // Here, var keyword is used // to create variables // Pname, Lname, and Cname // are the valid identifiers var Pname = "GeeksforGeeks" var Lname = "Go Language" var Cname = "Keywords" fmt.Printf("Portal name: %s", Pname) fmt.Printf("\nLanguage name: %s", Lname) fmt.Printf("\nChapter name: %s", Cname) } Output: Portal name: GeeksforGeeks Language name: Go Language Chapter name: Keywords Go-Basics Go-Keywords Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang 6 Best Books to Learn Go Programming Language time.Sleep() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Golang Maps Different Ways to Find the Type of Variable in Golang Inheritance in GoLang
[ { "code": null, "e": 26175, "s": 26147, "text": "\n03 Feb, 2020" }, { "code": null, "e": 26419, "s": 26175, "text": "Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error." }, { "code": null, "e": 26428, "s": 26419, "text": "Example:" }, { "code": "// Go program to illustrate the// use of keywordspackage mainimport \"fmt\" // Here, package, import, func,// var are keywordsfunc main() { // Here, a is a valid identifiervar a = \"GeeksforGeeks\" fmt.Println(a) // Here, the default is an// illegal identifier and// compiler will throw an error// var default = \"GFG\"}", "e": 26748, "s": 26428, "text": null }, { "code": null, "e": 26756, "s": 26748, "text": "Output:" }, { "code": null, "e": 26770, "s": 26756, "text": "GeeksforGeeks" }, { "code": null, "e": 26837, "s": 26770, "text": "There are total 25 keywords present in the Go language as follows:" }, { "code": null, "e": 26846, "s": 26837, "text": "Example:" }, { "code": "// Go program to illustrate // the use of keywords // Here package keyword is used to // include main package in the programpackage main // import keyword is used to // import \"fmt\" in your packageimport \"fmt\" // func is used to// create functionfunc main() { // Here, var keyword is used // to create variables // Pname, Lname, and Cname // are the valid identifiers var Pname = \"GeeksforGeeks\" var Lname = \"Go Language\" var Cname = \"Keywords\" fmt.Printf(\"Portal name: %s\", Pname) fmt.Printf(\"\\nLanguage name: %s\", Lname) fmt.Printf(\"\\nChapter name: %s\", Cname) }", "e": 27457, "s": 26846, "text": null }, { "code": null, "e": 27465, "s": 27457, "text": "Output:" }, { "code": null, "e": 27543, "s": 27465, "text": "Portal name: GeeksforGeeks\nLanguage name: Go Language\nChapter name: Keywords\n" }, { "code": null, "e": 27553, "s": 27543, "text": "Go-Basics" }, { "code": null, "e": 27565, "s": 27553, "text": "Go-Keywords" }, { "code": null, "e": 27572, "s": 27565, "text": "Golang" }, { "code": null, "e": 27584, "s": 27572, "text": "Go Language" }, { "code": null, "e": 27682, "s": 27584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27734, "s": 27682, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 27780, "s": 27734, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27826, "s": 27780, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 27876, "s": 27826, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 27902, "s": 27876, "text": "Time Formatting in Golang" }, { "code": null, "e": 27953, "s": 27902, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28000, "s": 27953, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28012, "s": 28000, "text": "Golang Maps" }, { "code": null, "e": 28066, "s": 28012, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Check if a point is inside, outside or on the ellipse in C++
Suppose, one ellipse is given (the center coordinate (h, k) and semi-major axis a, and semi-minor axis b), another point is also given. We have to find whether the point is inside the ellipse or not. To solve it, we have to solve the following equation for the given point (x, y). (x−h)2a2+(y−k)2b2≤1 If the result is less than one, then the point is inside the ellipse, otherwise not. Live Demo #include <iostream> #include <cmath> using namespace std; bool isInsideEllipse(int h, int k, int x, int y, int a, int b) { int res = (pow((x - h), 2) / pow(a, 2)) + (pow((y - k), 2) / pow(b, 2)); return res; } int main() { int x = 2, y = 1, h = 0, k = 0, a = 4, b = 5; if(isInsideEllipse(h, k, x, y, a, b) > 1){ cout <<"Outside Ellipse"; } else if(isInsideEllipse(h, k, x, y, a, b) == 1){ cout <<"On the Ellipse"; } else{ cout <<"Inside Ellipse"; } } Inside Ellipse
[ { "code": null, "e": 1343, "s": 1062, "text": "Suppose, one ellipse is given (the center coordinate (h, k) and semi-major axis a, and semi-minor axis b), another point is also given. We have to find whether the point is inside the ellipse or not. To solve it, we have to solve the following equation for the given point (x, y)." }, { "code": null, "e": 1363, "s": 1343, "text": "(x−h)2a2+(y−k)2b2≤1" }, { "code": null, "e": 1448, "s": 1363, "text": "If the result is less than one, then the point is inside the ellipse, otherwise not." }, { "code": null, "e": 1459, "s": 1448, "text": " Live Demo" }, { "code": null, "e": 1952, "s": 1459, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nbool isInsideEllipse(int h, int k, int x, int y, int a, int b) {\n int res = (pow((x - h), 2) / pow(a, 2)) + (pow((y - k), 2) / pow(b, 2));\n return res;\n}\nint main() {\n int x = 2, y = 1, h = 0, k = 0, a = 4, b = 5;\n if(isInsideEllipse(h, k, x, y, a, b) > 1){\n cout <<\"Outside Ellipse\";\n }\n else if(isInsideEllipse(h, k, x, y, a, b) == 1){\n cout <<\"On the Ellipse\";\n } else{\n cout <<\"Inside Ellipse\";\n }\n}" }, { "code": null, "e": 1967, "s": 1952, "text": "Inside Ellipse" } ]
How to remove Tableau Server users who own content | by Elliott Stam | Towards Data Science
This is also covered in our YouTube channel (Devyx): check it out. Breakups are hard. Tableau users come and go, and lucky for us we have some tools at our fingertips that can help us make a clean break to avoid the unpleasant nuances of dealing with orphaned content. This article explores one approach to making the removal of Tableau Server users a painless process. Whether your team adds and removes users manually or employs a bit of automation, the topics covered in this tutorial can help simplify the process by making sure the users being removed no longer own any content on the server, preventing users from landing in the ‘unlicensed’ graveyard and ensuring that no content on your server belongs to an unlicensed user. This tutorial walks through using the Python tableau-api-lib package and is part of a series on how to tap Tableau Server like a keg, giving you control over Tableau Server’s REST API. These tutorials assume you have Python 3 installed already. If you do not have Python 3 yet, this will get you started: guide to install Python. When you remove a Tableau user who does not own any content, it’s a piece of cake. No errors pop up, and all you see is a pleasant confirmation message that the user has been removed successfully. However, if you attempt to remove a Tableau user who owns content, you will get an error message informing you that the user cannot be removed because they are listed as an owner of content on the server. When we try to remove a user who owns content, that user instead becomes a sort of Tableau zombie who is banished to the ‘unlicensed’ user role but still holds ownership of their content. Tableau doesn’t let any content become an orphan, so the owner’s spirit lingers around on Tableau Server until its unfinished business (content ownership) has been taken care of and the user can be removed completely. So what can we do about that? In this tutorial, we demonstrate using the REST API to do the following: Identify if the user being removed owns any contentIf the user owns content, designate a different user as the new ownerRemove the user Identify if the user being removed owns any content If the user owns content, designate a different user as the new owner Remove the user Let’s also highlight what objects a user can own in Tableau Server: WorkbooksDatasourcesFlowsProjects Workbooks Datasources Flows Projects Currently, the Tableau Server REST API does not support changing owners of projects. If your user owns a project, you will need to change that project ownership manually before removing the user (sorry, please don’t kill the messenger). If you’re like me and want to be able to use the REST API to change project owners, please get out and upvote the idea on the Tableau forums. Even if you’re a pro at these tutorials, do yourself a favor and pull the latest version of the library. pip install --upgrade tableau-api-lib New to this Python stuff? Don’t sweat it, you’ll catch on quick. Follow this getting started tutorial. That tutorial walks you through getting connected to Tableau Server using tableau-api-lib. Use the code below as a template for getting connected to your server. In future steps, we will build upon this boiler plate with one-off lines of code. At the end of the article, you’ll find a consolidated block of code you can copy / paste for your convenience. from tableau_api_lib import TableauServerConnectionfrom tableau_api_lib.utils.querying import queryingtableau_server_config = { 'my_env': { 'server': 'https://YourTableauServer.com', 'api_version': '<YOUR_API_VERSION>', 'username': '<YOUR_USERNAME>', 'password': '<YOUR_PASSWORD>', 'site_name': '<YOUR_SITE_NAME>', 'site_url': '<YOUR_SITE_CONTENT_URL>' }}conn = TableauServerConnection(tableau_server_config, env='my_env')conn.sign_in() Fun fact: you can also use personal access tokens, assuming you are on Tableau Server 2019.4 or newer. If you’re all about the access tokens, check out my article for details on how to use them. The first piece of this puzzle is building ourselves a list of every content owner on the server. Once we have this, we can do a simple check to see if the user we plan on removing appears as an owner of any content on the server. To build this comprehensive list of content owners, we need to: get all project ownersget all workbook ownersget all datasource ownersget all flow ownersconsolidate the relevant information from each of the items above get all project owners get all workbook owners get all datasource owners get all flow owners consolidate the relevant information from each of the items above The full code is provided as a GitHub gist at the end of this article, so I won’t detail every step here, but let’s highlight how the tableau-api-lib comes in handy here. Let’s use workbooks as an example. Here’s a pattern we can use to pull information for all our workbooks, which also allows us to extract information about the workbook owners. workbooks_df = querying.get_workbooks_dataframe(conn) The resulting workbooks_df will look like this: Now, zooming in on that ‘owner’ column, there’s a nugget of information in there that we’d like to extract. That nugget is the ‘id’ value for the user who owns the content. Let’s extract that nested dict / JSON value by using tableau-api-lib’s flatten_dict_column util function. workbooks_df = flatten_dict_column(workbooks_df, keys=['id'], col_name='owner') If you take a look at the complete code at the end of the article, you’ll notice that we also add a ‘content_type’ column to each DataFrame we create. workbooks_df['content_type'] = 'workbook' This is simply there so that when we iterate over all the content owned by the user, we can identify the appropriate REST API endpoint to use. There are different endpoints for updating workbooks, datasources, and flows, and we need to call the correct tableau-api-lib method depending on the content type being updated. If we follow this pattern for our workbooks, datasources, flows, and projects, then we can easily combine the resulting data (please see the code at the end of the article for an example of doing this). Since we are changing ownership of content in order to remove a user, we need to designate another Tableau user to take ownership of the content. There are several valid approaches to this process. You could randomly select any of your server administrator users and assign the content to one of them, you could select a user by name, or you could cherry pick user ID values and select whichever one tickles your fancy. For this example, my test environment had a grand total of... two users. So I just called out my other user by name, like so: new_owner_id = list(users_df[users_df['name'] == 'estam']['id']).pop() The user whose username is ‘estam’ will be the new owner of any content that was previously owned by the user who is being removed. Speaking of the user being removed, I define that in my workflow as well: user_id_to_remove = list(users_df[users_df['name'] == 'estam2']['id']).pop() Again, there are many valid ways to define these values. All that matters is that you have a user ID for the new owner, and a user ID for the user being removed. The implementation I ran with iterates over all content owned by the user who is being removed. For each piece of content owned by that user, a function named change_content_owner is called. For the exact details of how that function is defined, please see the full code at the end of this article. In summary, the function contains some if statements which execute different REST API update calls depending on the type of content being processed. If a workbook needs an ownership change, then the ‘Update Workbook’ REST API endpoint is invoked. If a flow needs an ownership, then the ‘Update Flow’ REST API endpoint is invoked. And so on, and so on. Now, given that projects cannot (yet) be updated via REST API calls, that is a bit inconvenient for us. Until this ability is added to the realm of REST API possibilities, we will need to change that ownership by hand. If you’re really into automation, you can modify the function I’ve defined here to trigger a Slack message or email if a user is being removed who owns a project. That message could alert your server administrator team that this user will need some manual attention to be successfully removed from the server. Here’s some sample output from my process running. In this demonstration, the user being removed owned a workbook and a datasource. Before we finish here, let’s recap on the limitations of the process and where those limitations come from. You cannot remove users who own contentYou must change ownership of all content owned by a user before you can successfully remove the userYou cannot change ownership of projects via REST API calls (hopefully this functionality will be added soon; go vote on it!)Attempting to remove users who own content will result in the user’s role being modified to ‘unlicensed’ but they will still own the content.When you change who owns a workbook or datasource, any embedded credentials are invalidated. You cannot remove users who own content You must change ownership of all content owned by a user before you can successfully remove the user You cannot change ownership of projects via REST API calls (hopefully this functionality will be added soon; go vote on it!) Attempting to remove users who own content will result in the user’s role being modified to ‘unlicensed’ but they will still own the content. When you change who owns a workbook or datasource, any embedded credentials are invalidated. Want to know more? Check out Tableau’s documentation on changing content ownership. That’s all for this tutorial on removing Tableau users who own content. It all boils down to not leaving any loose ends in terms of content ownership. If your users don’t own any content, it’s a piece of cake! If your users do own content, change ownership for your workbooks, datasources, and flows. If your users own projects, you’ll need to manually change the owner before being able to successfully remove the user from the server. Thanks for tuning in! Reach out if your team needs help with Tableau Server REST API automation. Use this GitHub gist as a template for integrating the concepts from this tutorial into your own workflow.
[ { "code": null, "e": 239, "s": 172, "text": "This is also covered in our YouTube channel (Devyx): check it out." }, { "code": null, "e": 441, "s": 239, "text": "Breakups are hard. Tableau users come and go, and lucky for us we have some tools at our fingertips that can help us make a clean break to avoid the unpleasant nuances of dealing with orphaned content." }, { "code": null, "e": 905, "s": 441, "text": "This article explores one approach to making the removal of Tableau Server users a painless process. Whether your team adds and removes users manually or employs a bit of automation, the topics covered in this tutorial can help simplify the process by making sure the users being removed no longer own any content on the server, preventing users from landing in the ‘unlicensed’ graveyard and ensuring that no content on your server belongs to an unlicensed user." }, { "code": null, "e": 1090, "s": 905, "text": "This tutorial walks through using the Python tableau-api-lib package and is part of a series on how to tap Tableau Server like a keg, giving you control over Tableau Server’s REST API." }, { "code": null, "e": 1235, "s": 1090, "text": "These tutorials assume you have Python 3 installed already. If you do not have Python 3 yet, this will get you started: guide to install Python." }, { "code": null, "e": 1432, "s": 1235, "text": "When you remove a Tableau user who does not own any content, it’s a piece of cake. No errors pop up, and all you see is a pleasant confirmation message that the user has been removed successfully." }, { "code": null, "e": 1637, "s": 1432, "text": "However, if you attempt to remove a Tableau user who owns content, you will get an error message informing you that the user cannot be removed because they are listed as an owner of content on the server." }, { "code": null, "e": 2043, "s": 1637, "text": "When we try to remove a user who owns content, that user instead becomes a sort of Tableau zombie who is banished to the ‘unlicensed’ user role but still holds ownership of their content. Tableau doesn’t let any content become an orphan, so the owner’s spirit lingers around on Tableau Server until its unfinished business (content ownership) has been taken care of and the user can be removed completely." }, { "code": null, "e": 2146, "s": 2043, "text": "So what can we do about that? In this tutorial, we demonstrate using the REST API to do the following:" }, { "code": null, "e": 2282, "s": 2146, "text": "Identify if the user being removed owns any contentIf the user owns content, designate a different user as the new ownerRemove the user" }, { "code": null, "e": 2334, "s": 2282, "text": "Identify if the user being removed owns any content" }, { "code": null, "e": 2404, "s": 2334, "text": "If the user owns content, designate a different user as the new owner" }, { "code": null, "e": 2420, "s": 2404, "text": "Remove the user" }, { "code": null, "e": 2488, "s": 2420, "text": "Let’s also highlight what objects a user can own in Tableau Server:" }, { "code": null, "e": 2522, "s": 2488, "text": "WorkbooksDatasourcesFlowsProjects" }, { "code": null, "e": 2532, "s": 2522, "text": "Workbooks" }, { "code": null, "e": 2544, "s": 2532, "text": "Datasources" }, { "code": null, "e": 2550, "s": 2544, "text": "Flows" }, { "code": null, "e": 2559, "s": 2550, "text": "Projects" }, { "code": null, "e": 2796, "s": 2559, "text": "Currently, the Tableau Server REST API does not support changing owners of projects. If your user owns a project, you will need to change that project ownership manually before removing the user (sorry, please don’t kill the messenger)." }, { "code": null, "e": 2938, "s": 2796, "text": "If you’re like me and want to be able to use the REST API to change project owners, please get out and upvote the idea on the Tableau forums." }, { "code": null, "e": 3043, "s": 2938, "text": "Even if you’re a pro at these tutorials, do yourself a favor and pull the latest version of the library." }, { "code": null, "e": 3081, "s": 3043, "text": "pip install --upgrade tableau-api-lib" }, { "code": null, "e": 3275, "s": 3081, "text": "New to this Python stuff? Don’t sweat it, you’ll catch on quick. Follow this getting started tutorial. That tutorial walks you through getting connected to Tableau Server using tableau-api-lib." }, { "code": null, "e": 3539, "s": 3275, "text": "Use the code below as a template for getting connected to your server. In future steps, we will build upon this boiler plate with one-off lines of code. At the end of the article, you’ll find a consolidated block of code you can copy / paste for your convenience." }, { "code": null, "e": 4080, "s": 3539, "text": "from tableau_api_lib import TableauServerConnectionfrom tableau_api_lib.utils.querying import queryingtableau_server_config = { 'my_env': { 'server': 'https://YourTableauServer.com', 'api_version': '<YOUR_API_VERSION>', 'username': '<YOUR_USERNAME>', 'password': '<YOUR_PASSWORD>', 'site_name': '<YOUR_SITE_NAME>', 'site_url': '<YOUR_SITE_CONTENT_URL>' }}conn = TableauServerConnection(tableau_server_config, env='my_env')conn.sign_in()" }, { "code": null, "e": 4275, "s": 4080, "text": "Fun fact: you can also use personal access tokens, assuming you are on Tableau Server 2019.4 or newer. If you’re all about the access tokens, check out my article for details on how to use them." }, { "code": null, "e": 4506, "s": 4275, "text": "The first piece of this puzzle is building ourselves a list of every content owner on the server. Once we have this, we can do a simple check to see if the user we plan on removing appears as an owner of any content on the server." }, { "code": null, "e": 4570, "s": 4506, "text": "To build this comprehensive list of content owners, we need to:" }, { "code": null, "e": 4725, "s": 4570, "text": "get all project ownersget all workbook ownersget all datasource ownersget all flow ownersconsolidate the relevant information from each of the items above" }, { "code": null, "e": 4748, "s": 4725, "text": "get all project owners" }, { "code": null, "e": 4772, "s": 4748, "text": "get all workbook owners" }, { "code": null, "e": 4798, "s": 4772, "text": "get all datasource owners" }, { "code": null, "e": 4818, "s": 4798, "text": "get all flow owners" }, { "code": null, "e": 4884, "s": 4818, "text": "consolidate the relevant information from each of the items above" }, { "code": null, "e": 5055, "s": 4884, "text": "The full code is provided as a GitHub gist at the end of this article, so I won’t detail every step here, but let’s highlight how the tableau-api-lib comes in handy here." }, { "code": null, "e": 5232, "s": 5055, "text": "Let’s use workbooks as an example. Here’s a pattern we can use to pull information for all our workbooks, which also allows us to extract information about the workbook owners." }, { "code": null, "e": 5286, "s": 5232, "text": "workbooks_df = querying.get_workbooks_dataframe(conn)" }, { "code": null, "e": 5334, "s": 5286, "text": "The resulting workbooks_df will look like this:" }, { "code": null, "e": 5613, "s": 5334, "text": "Now, zooming in on that ‘owner’ column, there’s a nugget of information in there that we’d like to extract. That nugget is the ‘id’ value for the user who owns the content. Let’s extract that nested dict / JSON value by using tableau-api-lib’s flatten_dict_column util function." }, { "code": null, "e": 5693, "s": 5613, "text": "workbooks_df = flatten_dict_column(workbooks_df, keys=['id'], col_name='owner')" }, { "code": null, "e": 5844, "s": 5693, "text": "If you take a look at the complete code at the end of the article, you’ll notice that we also add a ‘content_type’ column to each DataFrame we create." }, { "code": null, "e": 5886, "s": 5844, "text": "workbooks_df['content_type'] = 'workbook'" }, { "code": null, "e": 6207, "s": 5886, "text": "This is simply there so that when we iterate over all the content owned by the user, we can identify the appropriate REST API endpoint to use. There are different endpoints for updating workbooks, datasources, and flows, and we need to call the correct tableau-api-lib method depending on the content type being updated." }, { "code": null, "e": 6410, "s": 6207, "text": "If we follow this pattern for our workbooks, datasources, flows, and projects, then we can easily combine the resulting data (please see the code at the end of the article for an example of doing this)." }, { "code": null, "e": 6608, "s": 6410, "text": "Since we are changing ownership of content in order to remove a user, we need to designate another Tableau user to take ownership of the content. There are several valid approaches to this process." }, { "code": null, "e": 6830, "s": 6608, "text": "You could randomly select any of your server administrator users and assign the content to one of them, you could select a user by name, or you could cherry pick user ID values and select whichever one tickles your fancy." }, { "code": null, "e": 6956, "s": 6830, "text": "For this example, my test environment had a grand total of... two users. So I just called out my other user by name, like so:" }, { "code": null, "e": 7027, "s": 6956, "text": "new_owner_id = list(users_df[users_df['name'] == 'estam']['id']).pop()" }, { "code": null, "e": 7159, "s": 7027, "text": "The user whose username is ‘estam’ will be the new owner of any content that was previously owned by the user who is being removed." }, { "code": null, "e": 7233, "s": 7159, "text": "Speaking of the user being removed, I define that in my workflow as well:" }, { "code": null, "e": 7310, "s": 7233, "text": "user_id_to_remove = list(users_df[users_df['name'] == 'estam2']['id']).pop()" }, { "code": null, "e": 7472, "s": 7310, "text": "Again, there are many valid ways to define these values. All that matters is that you have a user ID for the new owner, and a user ID for the user being removed." }, { "code": null, "e": 7663, "s": 7472, "text": "The implementation I ran with iterates over all content owned by the user who is being removed. For each piece of content owned by that user, a function named change_content_owner is called." }, { "code": null, "e": 7771, "s": 7663, "text": "For the exact details of how that function is defined, please see the full code at the end of this article." }, { "code": null, "e": 8123, "s": 7771, "text": "In summary, the function contains some if statements which execute different REST API update calls depending on the type of content being processed. If a workbook needs an ownership change, then the ‘Update Workbook’ REST API endpoint is invoked. If a flow needs an ownership, then the ‘Update Flow’ REST API endpoint is invoked. And so on, and so on." }, { "code": null, "e": 8652, "s": 8123, "text": "Now, given that projects cannot (yet) be updated via REST API calls, that is a bit inconvenient for us. Until this ability is added to the realm of REST API possibilities, we will need to change that ownership by hand. If you’re really into automation, you can modify the function I’ve defined here to trigger a Slack message or email if a user is being removed who owns a project. That message could alert your server administrator team that this user will need some manual attention to be successfully removed from the server." }, { "code": null, "e": 8784, "s": 8652, "text": "Here’s some sample output from my process running. In this demonstration, the user being removed owned a workbook and a datasource." }, { "code": null, "e": 8892, "s": 8784, "text": "Before we finish here, let’s recap on the limitations of the process and where those limitations come from." }, { "code": null, "e": 9389, "s": 8892, "text": "You cannot remove users who own contentYou must change ownership of all content owned by a user before you can successfully remove the userYou cannot change ownership of projects via REST API calls (hopefully this functionality will be added soon; go vote on it!)Attempting to remove users who own content will result in the user’s role being modified to ‘unlicensed’ but they will still own the content.When you change who owns a workbook or datasource, any embedded credentials are invalidated." }, { "code": null, "e": 9429, "s": 9389, "text": "You cannot remove users who own content" }, { "code": null, "e": 9530, "s": 9429, "text": "You must change ownership of all content owned by a user before you can successfully remove the user" }, { "code": null, "e": 9655, "s": 9530, "text": "You cannot change ownership of projects via REST API calls (hopefully this functionality will be added soon; go vote on it!)" }, { "code": null, "e": 9797, "s": 9655, "text": "Attempting to remove users who own content will result in the user’s role being modified to ‘unlicensed’ but they will still own the content." }, { "code": null, "e": 9890, "s": 9797, "text": "When you change who owns a workbook or datasource, any embedded credentials are invalidated." }, { "code": null, "e": 9974, "s": 9890, "text": "Want to know more? Check out Tableau’s documentation on changing content ownership." }, { "code": null, "e": 10125, "s": 9974, "text": "That’s all for this tutorial on removing Tableau users who own content. It all boils down to not leaving any loose ends in terms of content ownership." }, { "code": null, "e": 10184, "s": 10125, "text": "If your users don’t own any content, it’s a piece of cake!" }, { "code": null, "e": 10411, "s": 10184, "text": "If your users do own content, change ownership for your workbooks, datasources, and flows. If your users own projects, you’ll need to manually change the owner before being able to successfully remove the user from the server." }, { "code": null, "e": 10508, "s": 10411, "text": "Thanks for tuning in! Reach out if your team needs help with Tableau Server REST API automation." } ]
How to Convert CSV to Excel in Node.js ? - GeeksforGeeks
30 Jun, 2021 NodeJS has become one of the famous backend frameworks for development. So in this article, we’ll see one of its use to convert CSV into Excel We will use CSVtoExcel npm package to do the conversion of files. It provides convertCsvToXlsx function to implement the conversion. convertCsvToXlsx(source, destination); Steps to Implement: Import path and csv-to-xlsx module. Specify the source and destination directory and the file name with path module function. Use try catch block for error detection. Call the convert function to convert csv to excel function. Check the destination directory, you’ll see excel file. Modules Required: path: This module is used to join the path. csv-to-xlsx: This module provides functionality to convert csv to excel file. Creating Nodejs Application And Installing Module: Step 1: Run NPM init in cli and Enter the basic informationnpm init Step 1: Run NPM init in cli and Enter the basic information npm init Step 2:Now, create app.js or index.js or anything in which we’ll implement our functiontouch app.js Step 2:Now, create app.js or index.js or anything in which we’ll implement our function touch app.js Step 3: After creating the Nodejs application, Install the required modules using the following command:npm i path @aternur/csv-to-xlsx Step 3: After creating the Nodejs application, Install the required modules using the following command: npm i path @aternur/csv-to-xlsx Project Structure: It will look like the following. Report.csv File Code: Javascript // Importing modulesconst path = require('path');const convertCsvToXlsx = require('@aternus/csv-to-xlsx'); // Specifying source directory + file namelet source = path.join(__dirname, 'report.csv'); // Specifying destination directory + file namelet destination = path.join(__dirname, 'converted_report.xlsx'); // try-catch block for handling exceptionstry { // Functions to convert csv to excel convertCsvToXlsx(source, destination);} catch (e) { // Handling error console.error(e.toString());} Output: Excel File: NodeJS-Questions Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25028, "s": 25000, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25171, "s": 25028, "text": "NodeJS has become one of the famous backend frameworks for development. So in this article, we’ll see one of its use to convert CSV into Excel" }, { "code": null, "e": 25304, "s": 25171, "text": "We will use CSVtoExcel npm package to do the conversion of files. It provides convertCsvToXlsx function to implement the conversion." }, { "code": null, "e": 25343, "s": 25304, "text": "convertCsvToXlsx(source, destination);" }, { "code": null, "e": 25363, "s": 25343, "text": "Steps to Implement:" }, { "code": null, "e": 25399, "s": 25363, "text": "Import path and csv-to-xlsx module." }, { "code": null, "e": 25489, "s": 25399, "text": "Specify the source and destination directory and the file name with path module function." }, { "code": null, "e": 25530, "s": 25489, "text": "Use try catch block for error detection." }, { "code": null, "e": 25590, "s": 25530, "text": "Call the convert function to convert csv to excel function." }, { "code": null, "e": 25646, "s": 25590, "text": "Check the destination directory, you’ll see excel file." }, { "code": null, "e": 25664, "s": 25646, "text": "Modules Required:" }, { "code": null, "e": 25708, "s": 25664, "text": "path: This module is used to join the path." }, { "code": null, "e": 25786, "s": 25708, "text": "csv-to-xlsx: This module provides functionality to convert csv to excel file." }, { "code": null, "e": 25839, "s": 25788, "text": "Creating Nodejs Application And Installing Module:" }, { "code": null, "e": 25907, "s": 25839, "text": "Step 1: Run NPM init in cli and Enter the basic informationnpm init" }, { "code": null, "e": 25967, "s": 25907, "text": "Step 1: Run NPM init in cli and Enter the basic information" }, { "code": null, "e": 25976, "s": 25967, "text": "npm init" }, { "code": null, "e": 26076, "s": 25976, "text": "Step 2:Now, create app.js or index.js or anything in which we’ll implement our functiontouch app.js" }, { "code": null, "e": 26164, "s": 26076, "text": "Step 2:Now, create app.js or index.js or anything in which we’ll implement our function" }, { "code": null, "e": 26177, "s": 26164, "text": "touch app.js" }, { "code": null, "e": 26313, "s": 26177, "text": "Step 3: After creating the Nodejs application, Install the required modules using the following command:npm i path @aternur/csv-to-xlsx" }, { "code": null, "e": 26418, "s": 26313, "text": "Step 3: After creating the Nodejs application, Install the required modules using the following command:" }, { "code": null, "e": 26450, "s": 26418, "text": "npm i path @aternur/csv-to-xlsx" }, { "code": null, "e": 26502, "s": 26450, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26518, "s": 26502, "text": "Report.csv File" }, { "code": null, "e": 26524, "s": 26518, "text": "Code:" }, { "code": null, "e": 26535, "s": 26524, "text": "Javascript" }, { "code": "// Importing modulesconst path = require('path');const convertCsvToXlsx = require('@aternus/csv-to-xlsx'); // Specifying source directory + file namelet source = path.join(__dirname, 'report.csv'); // Specifying destination directory + file namelet destination = path.join(__dirname, 'converted_report.xlsx'); // try-catch block for handling exceptionstry { // Functions to convert csv to excel convertCsvToXlsx(source, destination);} catch (e) { // Handling error console.error(e.toString());}", "e": 27049, "s": 26535, "text": null }, { "code": null, "e": 27057, "s": 27049, "text": "Output:" }, { "code": null, "e": 27069, "s": 27057, "text": "Excel File:" }, { "code": null, "e": 27086, "s": 27069, "text": "NodeJS-Questions" }, { "code": null, "e": 27094, "s": 27086, "text": "Node.js" }, { "code": null, "e": 27111, "s": 27094, "text": "Web Technologies" }, { "code": null, "e": 27209, "s": 27111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27246, "s": 27209, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27278, "s": 27246, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27309, "s": 27278, "text": "Express.js req.params Property" }, { "code": null, "e": 27336, "s": 27309, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27383, "s": 27336, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27425, "s": 27383, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27468, "s": 27425, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27518, "s": 27468, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27580, "s": 27518, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Flutter - State Management
Managing state in an application is one of the most important and necessary process in the life cycle of an application. Let us consider a simple shopping cart application. User will login using their credentials into the application. User will login using their credentials into the application. Once user is logged in, the application should persist the logged in user detail in all the screen. Once user is logged in, the application should persist the logged in user detail in all the screen. Again, when the user selects a product and saved into a cart, the cart information should persist between the pages until the user checked out the cart. Again, when the user selects a product and saved into a cart, the cart information should persist between the pages until the user checked out the cart. User and their cart information at any instance is called the state of the application at that instance. User and their cart information at any instance is called the state of the application at that instance. A state management can be divided into two categories based on the duration the particular state lasts in an application. Ephemeral − Last for a few seconds like the current state of an animation or a single page like current rating of a product. Flutter supports its through StatefulWidget. Ephemeral − Last for a few seconds like the current state of an animation or a single page like current rating of a product. Flutter supports its through StatefulWidget. app state − Last for entire application like logged in user details, cart information, etc., Flutter supports its through scoped_model. app state − Last for entire application like logged in user details, cart information, etc., Flutter supports its through scoped_model. In any application, navigating from one page / screen to another defines the work flow of the application. The way that the navigation of an application is handled is called Routing. Flutter provides a basic routing class – MaterialPageRoute and two methods - Navigator.push and Navigator.pop, to define the work flow of an application. MaterialPageRoute is a widget used to render its UI by replacing the entire screen with a platform specific animation. MaterialPageRoute(builder: (context) => Widget()) Here, builder will accepts a function to build its content by suppling the current context of the application. Navigation.push is used to navigate to new screen using MaterialPageRoute widget. Navigator.push( context, MaterialPageRoute(builder: (context) => Widget()), ); Navigation.pop is used to navigate to previous screen. Navigator.push(context); Let us create a new application to better understand the navigation concept. Create a new Flutter application in Android studio, product_nav_app Copy the assets folder from product_nav_app to product_state_app and add assets inside the pubspec.yaml file. Copy the assets folder from product_nav_app to product_state_app and add assets inside the pubspec.yaml file. flutter: assets: - assets/appimages/floppy.png - assets/appimages/iphone.png - assets/appimages/laptop.png - assets/appimages/pendrive.png - assets/appimages/pixel.png - assets/appimages/tablet.png Replace the default startup code (main.dart) with our startup code. Replace the default startup code (main.dart) with our startup code. import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage( title: 'Product state demo home page' ), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.title), ), body: Center( child: Text('Hello World',) ), ); } } Let us create a Product class to organize the product information. Let us create a Product class to organize the product information. class Product { final String name; final String description; final int price; final String image; Product(this.name, this.description, this.price, this.image); } Let us write a method getProducts in the Product class to generate our dummy product records. Let us write a method getProducts in the Product class to generate our dummy product records. static List<Product> getProducts() { List<Product> items = <Product>[]; items.add( Product( "Pixel", "Pixel is the most feature-full phone ever", 800, "pixel.png" ) ); items.add( Product( "Laptop", "Laptop is most productive development tool", 2000, " laptop.png" ) ); items.add( Product( "Tablet", "Tablet is the most useful device ever for meeting", 1500, "tablet.png" ) ); items.add( Product( "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png" ) ); items.add( Product( "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png" ) ); return items; } import product.dart in main.dart import 'Product.dart'; Let us include our new widget, RatingBox. Let us include our new widget, RatingBox. class RatingBox extends StatefulWidget { @override _RatingBoxState createState() =>_RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState(() { _rating = 1; }); } void _setRatingAsTwo() { setState(() { _rating = 2; }); } void _setRatingAsThree() { setState(() { _rating = 3; }); } Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 1? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 2? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 3 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } } Let us modify our ProductBox widget to work with our new Product class. Let us modify our ProductBox widget to work with our new Product class. class ProductBox extends StatelessWidget { ProductBox({Key key, this.item}) : super(key: key); final Product item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description), Text("Price: " + this.item.price.toString()), RatingBox(), ], ) ) ) ] ), ) ); } } Let us rewrite our MyHomePage widget to work with Product model and to list all products using ListView. class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; final items = Product.getProducts(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Product Navigation")), body: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return GestureDetector( child: ProductBox(item: items[index]), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductPage(item: items[index]), ), ); }, ); }, )); } } Here, we have used MaterialPageRoute to navigate to product details page. Now, let us add ProductPage to show the product details. Now, let us add ProductPage to show the product details. class ProductPage extends StatelessWidget { ProductPage({Key key, this.item}) : super(key: key); final Product item; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.item.name), ), body: Center( child: Container( padding: EdgeInsets.all(0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text( this.item.name, style: TextStyle( fontWeight: FontWeight.bold ) ), Text(this.item.description), Text("Price: " + this.item.price.toString()), RatingBox(), ], ) ) ) ] ), ), ), ); } } The complete code of the application is as follows − import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class Product { final String name; final String description; final int price; final String image; Product(this.name, this.description, this.price, this.image); static List<Product> getProducts() { List<Product> items = <Product>[]; items.add( Product( "Pixel", "Pixel is the most featureful phone ever", 800, "pixel.png" ) ); items.add( Product( "Laptop", "Laptop is most productive development tool", 2000, "laptop.png" ) ); items.add( Product( "Tablet", "Tablet is the most useful device ever for meeting", 1500, "tablet.png" ) ); items.add( Product( "Pendrive", "iPhone is the stylist phone ever", 100, "pendrive.png" ) ); items.add( Product( "Floppy Drive", "iPhone is the stylist phone ever", 20, "floppy.png" ) ); items.add( Product( "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png" ) ); return items; } } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Product Navigation demo home page'), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; final items = Product.getProducts(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Product Navigation")), body: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return GestureDetector( child: ProductBox(item: items[index]), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductPage(item: items[index]), ), ); }, ); }, ) ); } } class ProductPage extends StatelessWidget { ProductPage({Key key, this.item}) : super(key: key); final Product item; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.item.name), ), body: Center( child: Container( padding: EdgeInsets.all(0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description), Text("Price: " + this.item.price.toString()), RatingBox(), ], ) ) ) ] ), ), ), ); } } class RatingBox extends StatefulWidget { @override _RatingBoxState createState() => _RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState(() { _rating = 1; }); } void _setRatingAsTwo() { setState(() { _rating = 2; }); } void _setRatingAsThree() { setState(() { _rating = 3; }); } Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 1 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 2 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 3 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } } class ProductBox extends StatelessWidget { ProductBox({Key key, this.item}) : super(key: key); final Product item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description), Text("Price: " + this.item.price.toString()), RatingBox(), ], ) ) ) ] ), ) ); } } Run the application and click any one of the product item. It will show the relevant details page. We can move to home page by clicking back button. The product list page and product details page of the application are shown as follows − 34 Lectures 4 hours Sriyank Siddhartha 117 Lectures 10 hours Frahaan Hussain 27 Lectures 1 hours Skillbakerystudios 17 Lectures 51 mins Harsh Kumar Khatri 17 Lectures 1.5 hours Pramila Rawat 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2339, "s": 2218, "text": "Managing state in an application is one of the most important and necessary process in the life cycle of an application." }, { "code": null, "e": 2391, "s": 2339, "text": "Let us consider a simple shopping cart application." }, { "code": null, "e": 2453, "s": 2391, "text": "User will login using their credentials into the application." }, { "code": null, "e": 2515, "s": 2453, "text": "User will login using their credentials into the application." }, { "code": null, "e": 2615, "s": 2515, "text": "Once user is logged in, the application should persist the logged in user detail in all the screen." }, { "code": null, "e": 2715, "s": 2615, "text": "Once user is logged in, the application should persist the logged in user detail in all the screen." }, { "code": null, "e": 2868, "s": 2715, "text": "Again, when the user selects a product and saved into a cart, the cart information should persist between the pages until the user checked out the cart." }, { "code": null, "e": 3021, "s": 2868, "text": "Again, when the user selects a product and saved into a cart, the cart information should persist between the pages until the user checked out the cart." }, { "code": null, "e": 3126, "s": 3021, "text": "User and their cart information at any instance is called the state of the application at that instance." }, { "code": null, "e": 3231, "s": 3126, "text": "User and their cart information at any instance is called the state of the application at that instance." }, { "code": null, "e": 3353, "s": 3231, "text": "A state management can be divided into two categories based on the duration the particular state lasts in an application." }, { "code": null, "e": 3523, "s": 3353, "text": "Ephemeral − Last for a few seconds like the current state of an animation or a single page like current rating of a product. Flutter supports its through StatefulWidget." }, { "code": null, "e": 3693, "s": 3523, "text": "Ephemeral − Last for a few seconds like the current state of an animation or a single page like current rating of a product. Flutter supports its through StatefulWidget." }, { "code": null, "e": 3830, "s": 3693, "text": "app state − Last for entire application like logged in user details, cart information, etc., Flutter supports its through scoped_model." }, { "code": null, "e": 3967, "s": 3830, "text": "app state − Last for entire application like logged in user details, cart information, etc., Flutter supports its through scoped_model." }, { "code": null, "e": 4304, "s": 3967, "text": "In any application, navigating from one page / screen to another defines the work flow of the application. The way that the navigation of an application is handled is called Routing. Flutter provides a basic routing class – MaterialPageRoute and two methods - Navigator.push and Navigator.pop, to define the work flow of an application." }, { "code": null, "e": 4423, "s": 4304, "text": "MaterialPageRoute is a widget used to render its UI by replacing the entire screen with a platform specific animation." }, { "code": null, "e": 4474, "s": 4423, "text": "MaterialPageRoute(builder: (context) => Widget())\n" }, { "code": null, "e": 4585, "s": 4474, "text": "Here, builder will accepts a function to build its content by suppling the current context of the application." }, { "code": null, "e": 4667, "s": 4585, "text": "Navigation.push is used to navigate to new screen using MaterialPageRoute widget." }, { "code": null, "e": 4747, "s": 4667, "text": "Navigator.push( context, MaterialPageRoute(builder: (context) => Widget()), );\n" }, { "code": null, "e": 4802, "s": 4747, "text": "Navigation.pop is used to navigate to previous screen." }, { "code": null, "e": 4828, "s": 4802, "text": "Navigator.push(context);\n" }, { "code": null, "e": 4905, "s": 4828, "text": "Let us create a new application to better understand the navigation concept." }, { "code": null, "e": 4973, "s": 4905, "text": "Create a new Flutter application in Android studio, product_nav_app" }, { "code": null, "e": 5083, "s": 4973, "text": "Copy the assets folder from product_nav_app to product_state_app and add assets inside the pubspec.yaml file." }, { "code": null, "e": 5193, "s": 5083, "text": "Copy the assets folder from product_nav_app to product_state_app and add assets inside the pubspec.yaml file." }, { "code": null, "e": 5419, "s": 5193, "text": "flutter:\n assets: \n - assets/appimages/floppy.png \n - assets/appimages/iphone.png \n - assets/appimages/laptop.png \n - assets/appimages/pendrive.png \n - assets/appimages/pixel.png \n - assets/appimages/tablet.png\n" }, { "code": null, "e": 5487, "s": 5419, "text": "Replace the default startup code (main.dart) with our startup code." }, { "code": null, "e": 5555, "s": 5487, "text": "Replace the default startup code (main.dart) with our startup code." }, { "code": null, "e": 6392, "s": 5555, "text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass MyApp extends StatelessWidget { \n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) { \n return MaterialApp( \n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage(\n title: 'Product state demo home page'\n ),\n );\n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key);\n final String title;\n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text(this.title), \n ), \n body: Center(\n child: Text('Hello World',)\n ), \n ); \n } \n}" }, { "code": null, "e": 6459, "s": 6392, "text": "Let us create a Product class to organize the product information." }, { "code": null, "e": 6526, "s": 6459, "text": "Let us create a Product class to organize the product information." }, { "code": null, "e": 6709, "s": 6526, "text": "class Product { \n final String name; \n final String description; \n final int price; \n final String image; \n Product(this.name, this.description, this.price, this.image); \n}" }, { "code": null, "e": 6803, "s": 6709, "text": "Let us write a method getProducts in the Product class to generate our dummy product records." }, { "code": null, "e": 6897, "s": 6803, "text": "Let us write a method getProducts in the Product class to generate our dummy product records." }, { "code": null, "e": 7839, "s": 6897, "text": "static List<Product> getProducts() {\n List<Product> items = <Product>[]; \n \n items.add(\n Product( \n \"Pixel\", \n \"Pixel is the most feature-full phone ever\", 800, \n \"pixel.png\"\n )\n ); \n items.add(\n Product(\n \"Laptop\", \n \"Laptop is most productive development tool\", \n 2000, \"\n laptop.png\"\n )\n ); \n items.add(\n Product( \n \"Tablet\", \n \"Tablet is the most useful device ever for meeting\", \n 1500, \n \"tablet.png\"\n )\n ); \n items.add(\n Product( \n \"Pendrive\", \n \"Pendrive is useful storage medium\",\n 100, \n \"pendrive.png\"\n )\n ); \n items.add(\n Product( \n \"Floppy Drive\", \n \"Floppy drive is useful rescue storage medium\", \n 20, \n \"floppy.png\"\n )\n ); \n return items; \n}\nimport product.dart in main.dart\nimport 'Product.dart';" }, { "code": null, "e": 7881, "s": 7839, "text": "Let us include our new widget, RatingBox." }, { "code": null, "e": 7923, "s": 7881, "text": "Let us include our new widget, RatingBox." }, { "code": null, "e": 10505, "s": 7923, "text": "class RatingBox extends StatefulWidget {\n @override \n _RatingBoxState createState() =>_RatingBoxState(); \n} \nclass _RatingBoxState extends State<RatingBox> {\n int _rating = 0; \n void _setRatingAsOne() {\n setState(() {\n _rating = 1; \n }); \n } \n void _setRatingAsTwo() {\n setState(() {\n _rating = 2; \n }); \n }\n void _setRatingAsThree() {\n setState(() {\n _rating = 3;\n });\n }\n Widget build(BuildContext context) {\n double _size = 20; \n print(_rating); \n return Row(\n mainAxisAlignment: MainAxisAlignment.end, \n crossAxisAlignment: CrossAxisAlignment.end, \n mainAxisSize: MainAxisSize.max, \n children: <Widget>[\n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (\n _rating >= 1? \n Icon( \n Icons.star, \n size: _size, \n ) \n : Icon(\n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsOne, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (\n _rating >= 2? \n Icon(\n Icons.star, \n size: _size, \n ) \n : Icon(\n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsTwo, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (\n _rating >= 3 ? \n Icon(\n Icons.star, \n size: _size, \n ) \n : Icon( \n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsThree, \n iconSize: _size, \n ), \n ), \n ], \n ); \n }\n}" }, { "code": null, "e": 10577, "s": 10505, "text": "Let us modify our ProductBox widget to work with our new Product class." }, { "code": null, "e": 10649, "s": 10577, "text": "Let us modify our ProductBox widget to work with our new Product class." }, { "code": null, "e": 11882, "s": 10649, "text": "class ProductBox extends StatelessWidget { \n ProductBox({Key key, this.item}) : super(key: key); \n final Product item; \n \n Widget build(BuildContext context) {\n return Container(\n padding: EdgeInsets.all(2), \n height: 140, \n child: Card( \n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Image.asset(\"assets/appimages/\" + this.item.image), \n Expanded(\n child: Container(\n padding: EdgeInsets.all(5), \n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[\n Text(this.item.name, \n style: TextStyle(fontWeight: FontWeight.bold)), \n Text(this.item.description), \n Text(\"Price: \" + this.item.price.toString()), \n RatingBox(), \n ], \n )\n )\n )\n ]\n ), \n )\n ); \n }\n}" }, { "code": null, "e": 11987, "s": 11882, "text": "Let us rewrite our MyHomePage widget to work with Product model and to list all products using ListView." }, { "code": null, "e": 12793, "s": 11987, "text": "class MyHomePage extends StatelessWidget { \n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n final items = Product.getProducts(); \n \n @override \n Widget build(BuildContext context) { \n return Scaffold( appBar: AppBar(title: Text(\"Product Navigation\")), \n body: ListView.builder( \n itemCount: items.length, \n itemBuilder: (context, index) {\n return GestureDetector( \n child: ProductBox(item: items[index]), \n onTap: () { \n Navigator.push( \n context, MaterialPageRoute( \n builder: (context) => ProductPage(item: items[index]), \n ), \n ); \n }, \n ); \n }, \n )); \n } \n}" }, { "code": null, "e": 12867, "s": 12793, "text": "Here, we have used MaterialPageRoute to navigate to product details page." }, { "code": null, "e": 12924, "s": 12867, "text": "Now, let us add ProductPage to show the product details." }, { "code": null, "e": 12981, "s": 12924, "text": "Now, let us add ProductPage to show the product details." }, { "code": null, "e": 14576, "s": 12981, "text": "class ProductPage extends StatelessWidget { \n ProductPage({Key key, this.item}) : super(key: key); \n final Product item; \n \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar( \n title: Text(this.item.name), \n ), \n body: Center(\n child: Container(\n padding: EdgeInsets.all(0), \n child: Column(\n mainAxisAlignment: MainAxisAlignment.start, \n crossAxisAlignment: CrossAxisAlignment.start, \n children: <Widget>[\n Image.asset(\"assets/appimages/\" + this.item.image), \n Expanded(\n child: Container(\n padding: EdgeInsets.all(5), \n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[\n Text(\n this.item.name, style: TextStyle(\n fontWeight: FontWeight.bold\n )\n ), \n Text(this.item.description), \n Text(\"Price: \" + this.item.price.toString()), \n RatingBox(),\n ], \n )\n )\n )\n ]\n ), \n ), \n ), \n ); \n } \n}" }, { "code": null, "e": 14629, "s": 14576, "text": "The complete code of the application is as follows −" }, { "code": null, "e": 22532, "s": 14629, "text": "import 'package:flutter/material.dart'; \nvoid main() => runApp(MyApp()); \n\nclass Product {\n final String name; \n final String description; \n final int price; \n final String image; \n Product(this.name, this.description, this.price, this.image); \n \n static List<Product> getProducts() {\n List<Product> items = <Product>[]; \n items.add(\n Product(\n \"Pixel\", \n \"Pixel is the most featureful phone ever\", \n 800, \n \"pixel.png\"\n )\n );\n items.add(\n Product(\n \"Laptop\", \n \"Laptop is most productive development tool\", \n 2000, \n \"laptop.png\"\n )\n ); \n items.add(\n Product(\n \"Tablet\", \n \"Tablet is the most useful device ever for meeting\", \n 1500, \n \"tablet.png\"\n )\n ); \n items.add(\n Product( \n \"Pendrive\", \n \"iPhone is the stylist phone ever\", \n 100, \n \"pendrive.png\"\n )\n ); \n items.add(\n Product(\n \"Floppy Drive\", \n \"iPhone is the stylist phone ever\", \n 20, \n \"floppy.png\"\n )\n ); \n items.add(\n Product(\n \"iPhone\", \n \"iPhone is the stylist phone ever\", \n 1000, \n \"iphone.png\"\n )\n ); \n return items; \n }\n}\nclass MyApp extends StatelessWidget {\n // This widget is the root of your application. \n @override \n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo', \n theme: ThemeData( \n primarySwatch: Colors.blue, \n ), \n home: MyHomePage(title: 'Product Navigation demo home page'), \n ); \n }\n}\nclass MyHomePage extends StatelessWidget {\n MyHomePage({Key key, this.title}) : super(key: key); \n final String title; \n final items = Product.getProducts(); \n \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(title: Text(\"Product Navigation\")), \n body: ListView.builder( \n itemCount: items.length, \n itemBuilder: (context, index) { \n return GestureDetector( \n child: ProductBox(item: items[index]), \n onTap: () { \n Navigator.push( \n context, \n MaterialPageRoute( \n builder: (context) => ProductPage(item: items[index]), \n ), \n ); \n }, \n ); \n }, \n )\n ); \n }\n} \nclass ProductPage extends StatelessWidget {\n ProductPage({Key key, this.item}) : super(key: key); \n final Product item; \n \n @override \n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n title: Text(this.item.name), \n ), \n body: Center(\n child: Container( \n padding: EdgeInsets.all(0), \n child: Column( \n mainAxisAlignment: MainAxisAlignment.start, \n crossAxisAlignment: CrossAxisAlignment.start, \n children: <Widget>[ \n Image.asset(\"assets/appimages/\" + this.item.image), \n Expanded( \n child: Container( \n padding: EdgeInsets.all(5), \n child: Column( \n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), \n Text(this.item.description), \n Text(\"Price: \" + this.item.price.toString()), \n RatingBox(), \n ], \n )\n )\n ) \n ]\n ), \n ), \n ), \n ); \n } \n}\nclass RatingBox extends StatefulWidget { \n @override \n _RatingBoxState createState() => _RatingBoxState(); \n} \nclass _RatingBoxState extends State<RatingBox> { \n int _rating = 0;\n void _setRatingAsOne() {\n setState(() {\n _rating = 1; \n }); \n }\n void _setRatingAsTwo() {\n setState(() {\n _rating = 2; \n }); \n } \n void _setRatingAsThree() { \n setState(() {\n _rating = 3; \n }); \n }\n Widget build(BuildContext context) {\n double _size = 20; \n print(_rating); \n return Row(\n mainAxisAlignment: MainAxisAlignment.end, \n crossAxisAlignment: CrossAxisAlignment.end, \n mainAxisSize: MainAxisSize.max, \n children: <Widget>[\n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (\n _rating >= 1 ? Icon( \n Icons.star, \n size: _size, \n ) \n : Icon( \n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsOne, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0), \n child: IconButton( \n icon: (\n _rating >= 2 ? \n Icon( \n Icons.star, \n size: _size, \n ) \n : Icon( \n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsTwo, \n iconSize: _size, \n ), \n ), \n Container(\n padding: EdgeInsets.all(0), \n child: IconButton(\n icon: (\n _rating >= 3 ? \n Icon( \n Icons.star, \n size: _size, \n )\n : Icon( \n Icons.star_border, \n size: _size, \n )\n ), \n color: Colors.red[500], \n onPressed: _setRatingAsThree, \n iconSize: _size, \n ), \n ), \n ], \n ); \n } \n} \nclass ProductBox extends StatelessWidget {\n ProductBox({Key key, this.item}) : super(key: key); \n final Product item; \n \n Widget build(BuildContext context) {\n return Container(\n padding: EdgeInsets.all(2), \n height: 140, \n child: Card(\n child: Row(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Image.asset(\"assets/appimages/\" + this.item.image), \n Expanded( \n child: Container( \n padding: EdgeInsets.all(5), \n child: Column( \n mainAxisAlignment: MainAxisAlignment.spaceEvenly, \n children: <Widget>[ \n Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description), \n Text(\"Price: \" + this.item.price.toString()), \n RatingBox(), \n ], \n )\n )\n ) \n ]\n ), \n )\n ); \n } \n}" }, { "code": null, "e": 22770, "s": 22532, "text": "Run the application and click any one of the product item. It will show the relevant details page. We can move to home page by clicking back button. The product list page and product details page of the application are shown as follows −" }, { "code": null, "e": 22803, "s": 22770, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 22823, "s": 22803, "text": " Sriyank Siddhartha" }, { "code": null, "e": 22858, "s": 22823, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 22875, "s": 22858, "text": " Frahaan Hussain" }, { "code": null, "e": 22908, "s": 22875, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 22928, "s": 22908, "text": " Skillbakerystudios" }, { "code": null, "e": 22960, "s": 22928, "text": "\n 17 Lectures \n 51 mins\n" }, { "code": null, "e": 22980, "s": 22960, "text": " Harsh Kumar Khatri" }, { "code": null, "e": 23015, "s": 22980, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 23030, "s": 23015, "text": " Pramila Rawat" }, { "code": null, "e": 23066, "s": 23030, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 23081, "s": 23066, "text": " Rahul Agarwal" }, { "code": null, "e": 23088, "s": 23081, "text": " Print" }, { "code": null, "e": 23099, "s": 23088, "text": " Add Notes" } ]
C++ | Operator Overloading | Question 3 - GeeksforGeeks
28 Jun, 2021 Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? 1) Comparison Operator ( == ) 2) Assignment Operator ( = ) (A) Both 1 and 2(B) Only 1(C) Only 2(D) None of the twoAnswer: (C)Explanation: Assign operator is by default available in all user defined classes even if user has not implemented. The default assignement does shallow copy. But comparison operator “==” is not overloaded. #include<iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i =0) {real = r; imag = i;} }; int main() { Complex c1(10, 5), c2(2, 4); // For example, below code works fine c1 = c2; // But this code throws compiler error if (c1 == c2) cout << "Same"; return 0; } Quiz of this Question C++-Operator Overloading Operator Overloading C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Function Pointer in C C++ | Exception Handling | Question 3 C++ | Inheritance | Question 7 C++ | new and delete | Question 4 C++ | Inheritance | Question 1 C++ | Inheritance | Question 11
[ { "code": null, "e": 24729, "s": 24701, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24864, "s": 24729, "text": "Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written?" }, { "code": null, "e": 24924, "s": 24864, "text": "1) Comparison Operator ( == )\n2) Assignment Operator ( = ) " }, { "code": null, "e": 25148, "s": 24924, "text": "(A) Both 1 and 2(B) Only 1(C) Only 2(D) None of the twoAnswer: (C)Explanation: Assign operator is by default available in all user defined classes even if user has not implemented. The default assignement does shallow copy." }, { "code": null, "e": 25196, "s": 25148, "text": "But comparison operator “==” is not overloaded." }, { "code": null, "e": 25556, "s": 25196, "text": "#include<iostream>\nusing namespace std;\n\nclass Complex {\nprivate:\n int real, imag;\npublic:\n Complex(int r = 0, int i =0) {real = r; imag = i;}\n};\n\nint main()\n{\n Complex c1(10, 5), c2(2, 4);\n\n // For example, below code works fine\n c1 = c2;\n\n // But this code throws compiler error\n if (c1 == c2)\n cout << \"Same\";\n\n return 0;\n}" }, { "code": null, "e": 25578, "s": 25556, "text": "Quiz of this Question" }, { "code": null, "e": 25603, "s": 25578, "text": "C++-Operator Overloading" }, { "code": null, "e": 25624, "s": 25603, "text": "Operator Overloading" }, { "code": null, "e": 25635, "s": 25624, "text": "C Language" }, { "code": null, "e": 25644, "s": 25635, "text": "C++ Quiz" }, { "code": null, "e": 25742, "s": 25644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25770, "s": 25742, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25816, "s": 25770, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25828, "s": 25816, "text": "fork() in C" }, { "code": null, "e": 25860, "s": 25828, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25882, "s": 25860, "text": "Function Pointer in C" }, { "code": null, "e": 25920, "s": 25882, "text": "C++ | Exception Handling | Question 3" }, { "code": null, "e": 25951, "s": 25920, "text": "C++ | Inheritance | Question 7" }, { "code": null, "e": 25985, "s": 25951, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 26016, "s": 25985, "text": "C++ | Inheritance | Question 1" } ]
W3.CSS - Buttons
W3.CSS has a very beautiful and responsive CSS for customizing the look of a button. The following CSS are used − w3-btn Represents a standard button. Can be used to style a link as button as well. w3-btn-floating Represents a floating button being circular in design. w3-btn-floating-large Represents a large floating button. <html> <head> <title>The W3.CSS Forms</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css"> </head> <body class = "w3-container"> <h2>Standard Buttons</h2> <button class = "w3-btn">Click Me</button> <button class = "w3-btn w3-teal">Click Me</button> <button class = "w3-btn w3-disabled">I am disabled</button> <h2>Links as Buttons</h2> <a class = "w3-btn">Link</a> <a class = "w3-btn w3-teal">Link</a> <a class = "w3-btn w3-disabled">Disabled Link</a> <h2>Floating Buttons</h2> <a class = "w3-btn-floating">+</a> <a class = "w3-btn-floating w3-teal">+</a> <a class = "w3-btn-floating w3-disabled">+</a> <h2>Large Floating Buttons</h2> <a class = "w3-btn-floating-large">+</a> <a class = "w3-btn-floating-large w3-teal">+</a> <a class = "w3-btn-floating-large w3-disabled">+</a> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2023, "s": 1909, "text": "W3.CSS has a very beautiful and responsive CSS for customizing the look of a button. The following CSS are used −" }, { "code": null, "e": 2030, "s": 2023, "text": "w3-btn" }, { "code": null, "e": 2107, "s": 2030, "text": "Represents a standard button. Can be used to style a link as button as well." }, { "code": null, "e": 2123, "s": 2107, "text": "w3-btn-floating" }, { "code": null, "e": 2178, "s": 2123, "text": "Represents a floating button being circular in design." }, { "code": null, "e": 2200, "s": 2178, "text": "w3-btn-floating-large" }, { "code": null, "e": 2236, "s": 2200, "text": "Represents a large floating button." }, { "code": null, "e": 3284, "s": 2236, "text": "<html>\n <head>\n <title>The W3.CSS Forms</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://www.w3schools.com/lib/w3.css\">\n </head>\n \n <body class = \"w3-container\">\n <h2>Standard Buttons</h2>\n <button class = \"w3-btn\">Click Me</button>\n <button class = \"w3-btn w3-teal\">Click Me</button>\n <button class = \"w3-btn w3-disabled\">I am disabled</button>\n \n <h2>Links as Buttons</h2>\n <a class = \"w3-btn\">Link</a>\n <a class = \"w3-btn w3-teal\">Link</a>\n <a class = \"w3-btn w3-disabled\">Disabled Link</a>\n \n <h2>Floating Buttons</h2>\n <a class = \"w3-btn-floating\">+</a>\n <a class = \"w3-btn-floating w3-teal\">+</a>\n <a class = \"w3-btn-floating w3-disabled\">+</a>\n \n <h2>Large Floating Buttons</h2>\n <a class = \"w3-btn-floating-large\">+</a>\n <a class = \"w3-btn-floating-large w3-teal\">+</a>\n <a class = \"w3-btn-floating-large w3-disabled\">+</a>\n </body>\n</html>" }, { "code": null, "e": 3303, "s": 3284, "text": "Verify the result." }, { "code": null, "e": 3310, "s": 3303, "text": " Print" }, { "code": null, "e": 3321, "s": 3310, "text": " Add Notes" } ]
Are array members deeply copied in C++?
In case of C/C++, we can be able to assign a struct (or class in C++ only) variable to another variable of same type. At the time when we assign a struct variable to another, all members of the variable are copied to the other struct variable. In this case the question is arisen what happens when the structure consists of an array? Now, we have to discuss about arrays. Main point to note is that the array members is not copied as shallow copy; compiler automatically accomplishes Deep Copy in case of array members. In the below program, struct test consists of array member str1[]. When we are able to assign st1 to st2, st2 has a new copy of the array. So st2 is not modified or changed when we modify or change str[] of st1. Live Demo # include <iostream> # include <string.h> using namespace std; struct test{ char str1[20]; }; int main(){ struct test st1, st2; strcpy(st1.str1, "Tutorial Point"); st2 = st1; st1.str1[0] = 'X'; st1.str1[1] = 'Y'; /* Because copy was Deep, both arrays are different */ cout<< "st1's str = " << st1.str1 << endl; cout<< "st2's str = " << st2.str1 << endl; return 0; } st1's str = XYtorial Point st2's str = Tutorial Point Therefore, in case of C++ classes, we don’t require to write our own copy constructor and assignment operator for array members because the default behavior is Deep copy for arrays.
[ { "code": null, "e": 1396, "s": 1062, "text": "In case of C/C++, we can be able to assign a struct (or class in C++ only) variable to another variable of same type. At the time when we assign a struct variable to another, all members of the variable are copied to the other struct variable. In this case the question is arisen what happens when the structure consists of an array?" }, { "code": null, "e": 1794, "s": 1396, "text": "Now, we have to discuss about arrays. Main point to note is that the array members is not copied as shallow copy; compiler automatically accomplishes Deep Copy in case of array members. In the below program, struct test consists of array member str1[]. When we are able to assign st1 to st2, st2 has a new copy of the array. So st2 is not modified or changed when we modify or change str[] of st1." }, { "code": null, "e": 1805, "s": 1794, "text": " Live Demo" }, { "code": null, "e": 2201, "s": 1805, "text": "# include <iostream>\n# include <string.h>\nusing namespace std;\nstruct test{\n char str1[20];\n};\nint main(){\n struct test st1, st2;\n strcpy(st1.str1, \"Tutorial Point\");\n st2 = st1;\n st1.str1[0] = 'X';\n st1.str1[1] = 'Y';\n /* Because copy was Deep, both arrays are different */\n cout<< \"st1's str = \" << st1.str1 << endl;\n cout<< \"st2's str = \" << st2.str1 << endl;\n return 0;\n}" }, { "code": null, "e": 2255, "s": 2201, "text": "st1's str = XYtorial Point\nst2's str = Tutorial Point" }, { "code": null, "e": 2437, "s": 2255, "text": "Therefore, in case of C++ classes, we don’t require to write our own copy constructor and assignment operator for array members because the default behavior is Deep copy for arrays." } ]
How to remove a function from an object in JavaScript?
JSON.stringify() method not only stringifies an object but also removes any function present in an object. Lets' discuss it in detail. In the following example, the property 'designation' is a function so when we tried to stringify the object, the function was removed and other properties were displayed as shown in the output. Live Demo <html> <body> <p id="stringify"></p> <script> var person = { name: "Rahim", designation: function () {return developer;}, city: "Hyderabad" }; var myJSON = JSON.stringify(person); document.getElementById("stringify").innerHTML = myJSON; </script> </body> </html> {"name":"Rahim","city":"Hyderabad"} In the following example, the property 'name' is acting as a function so when we stringify the object using JSON.stringify(), the function was removed and other properties were displayed as shown in the output. Live Demo <html> <body> <p id="stringify"></p> <script> var person = { name: function () {return Ram + Rahim;}, designation:"Developer" , city: "Hyderabad" }; var myJSON = JSON.stringify(person); document.getElementById("stringify").innerHTML = myJSON; </script> </body> </html> {"designation":"Developer","city":"Hyderabad"}
[ { "code": null, "e": 1197, "s": 1062, "text": "JSON.stringify() method not only stringifies an object but also removes any function present in an object. Lets' discuss it in detail." }, { "code": null, "e": 1391, "s": 1197, "text": "In the following example, the property 'designation' is a function so when we tried to stringify the object, the function was removed and other properties were displayed as shown in the output." }, { "code": null, "e": 1401, "s": 1391, "text": "Live Demo" }, { "code": null, "e": 1697, "s": 1401, "text": "<html>\n<body>\n <p id=\"stringify\"></p>\n <script>\n var person = { name: \"Rahim\", designation: function () {return developer;},\n city: \"Hyderabad\" };\n var myJSON = JSON.stringify(person);\n document.getElementById(\"stringify\").innerHTML = myJSON;\n </script>\n</body>\n</html>" }, { "code": null, "e": 1733, "s": 1697, "text": "{\"name\":\"Rahim\",\"city\":\"Hyderabad\"}" }, { "code": null, "e": 1944, "s": 1733, "text": "In the following example, the property 'name' is acting as a function so when we stringify the object using JSON.stringify(), the function was removed and other properties were displayed as shown in the output." }, { "code": null, "e": 1954, "s": 1944, "text": "Live Demo" }, { "code": null, "e": 2256, "s": 1954, "text": "<html>\n<body>\n <p id=\"stringify\"></p>\n <script>\n var person = { name: function () {return Ram + Rahim;},\n designation:\"Developer\" , city: \"Hyderabad\" };\n var myJSON = JSON.stringify(person);\n document.getElementById(\"stringify\").innerHTML = myJSON;\n </script>\n</body>\n</html>" }, { "code": null, "e": 2303, "s": 2256, "text": "{\"designation\":\"Developer\",\"city\":\"Hyderabad\"}" } ]
Check if array contains contiguous integers with duplicates allowed - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more School Guide Python Programming Learn To Make Apps Explore more All Courses TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON Events WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Explore more School Guide Python Programming Learn To Make Apps Explore more Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Check if array contains contiguous integers with duplicates allowed Check if array elements are consecutive | Added Method 4 Find the smallest missing number Maximum sum such that no two elements are adjacent | Set 2 Maximum sum such that no two elements are adjacent Find maximum possible stolen value from houses Find number of solutions of a linear equation of n variables Count number of ways to reach a given score in a game Program for Fibonacci numbers Program for nth Catalan Number Bell Numbers (Number of ways to Partition a Set) Binomial Coefficient | DP-9 Permutation Coefficient Tiling Problem Gold Mine Problem Coin Change | DP-7 Find minimum number of coins that make a given value Greedy Algorithm to find Minimum number of Coins K Centers Problem | Set 1 (Greedy Approximate Algorithm) Minimum Number of Platforms Required for a Railway/Bus Station Reverse an array in groups of given size K’th Smallest/Largest Element in Unsorted Array | Set 1 K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) K’th Smallest/Largest Element using STL Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Check if array contains contiguous integers with duplicates allowed Check if array elements are consecutive | Added Method 4 Find the smallest missing number Maximum sum such that no two elements are adjacent | Set 2 Maximum sum such that no two elements are adjacent Find maximum possible stolen value from houses Find number of solutions of a linear equation of n variables Count number of ways to reach a given score in a game Program for Fibonacci numbers Program for nth Catalan Number Bell Numbers (Number of ways to Partition a Set) Binomial Coefficient | DP-9 Permutation Coefficient Tiling Problem Gold Mine Problem Coin Change | DP-7 Find minimum number of coins that make a given value Greedy Algorithm to find Minimum number of Coins K Centers Problem | Set 1 (Greedy Approximate Algorithm) Minimum Number of Platforms Required for a Railway/Bus Station Reverse an array in groups of given size K’th Smallest/Largest Element in Unsorted Array | Set 1 K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) K’th Smallest/Largest Element using STL Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Difficulty Level : Easy Given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous integers else print “No”. Examples: Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6} Output : Yes The elements form a contiguous set of integers which is {2, 3, 4, 5, 6}. Input : arr[] = {10, 14, 10, 12, 12, 13, 15} Output : No We have discussed different solutions for distinct elements in the below post. Check if array elements are consecutiveA simple solution is to first sort the array. Then traverse the array to check if all consecutive elements differ at most by one. C Java Python3 C# PHP Javascript // Sorting based C++ implementation// to check whether the array// contains a set of contiguous// integers#include <bits/stdc++.h>using namespace std; // function to check whether// the array contains a set// of contiguous integersbool areElementsContiguous(int arr[], int n){ // Sort the array sort(arr, arr+n); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i-1] > 1) return false; return true;} // Driver program to test aboveint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << "Yes"; else cout << "No"; return 0;} // Sorting based Java implementation// to check whether the array// contains a set of contiguous// integersimport java.util.*; class GFG { // function to check whether // the array contains a set // of contiguous integers static boolean areElementsContiguous(int arr[], int n) { // Sort the array Arrays.sort(arr); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i-1] > 1) return false; return true; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by Arnav Kr. Mandal. # Sorting based Python implementation# to check whether the array# contains a set of contiguous integers def areElementsContiguous(arr, n): # Sort the array arr.sort() # After sorting, check if # current element is either # same as previous or is # one more. for i in range(1,n): if (arr[i] - arr[i-1] > 1) : return 0 return 1 # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr)if areElementsContiguous(arr, n): print("Yes")else: print("No") # This code is contributed by 'Ansu Kumari'. // Sorting based C# implementation// to check whether the array// contains a set of contiguous// integersusing System; class GFG { // function to check whether // the array contains a set // of contiguous integers static bool areElementsContiguous(int []arr, int n) { // Sort the array Array.Sort(arr); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i - 1] > 1) return false; return true; } // Driver program public static void Main() { int []arr = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.Length; if (areElementsContiguous(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This code is contributed by Vt_m. <?php// Sorting based PHP implementation to check// whether the array contains a set of contiguous// integers // function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous($arr, $n){ // Sort the array sort($arr); // After sorting, check if current element // is either same as previous or is one more. for ($i = 1; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] > 1) return false; return true;} // Driver Code$arr = array( 5, 2, 3, 6, 4, 4, 6, 6 );$n = sizeof($arr); if (areElementsContiguous($arr, $n)) echo "Yes";else echo "No"; // This code is contributed by ajit?> <script> // Sorting based Javascript implementation // to check whether the array // contains a set of contiguous // integers // function to check whether // the array contains a set // of contiguous integers function areElementsContiguous(arr, n) { // Sort the array arr.sort(function(a, b){return a - b}); // After sorting, check if // current element is either // same as previous or is // one more. for (let i = 1; i < n; i++) if (arr[i] - arr[i - 1] > 1) return false; return true; } let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]; let n = arr.length; if (areElementsContiguous(arr, n)) document.write("Yes"); else document.write("No"); // This code is contributed by rameshtravel07.</script> Output: Yes Time Complexity: O(n Log n) Another Approach is :- if we can find the minimum element and maximum element that are present in the array and use the below procedure then we can say that the array contains contiguous elements or not. PROCEDURE :- 1) Store the elements in unordered set (So as to maintain the Time complexity of the problem i.e. O(n) ) 2) Find the minimum element present in the array and store it in a variable say min_ele. 3) Find the maximum element present in the array and store it in a variable say max_ele. 4) Now just think a little bit we can notice that if we Subtract the min_ele from the max_ele and add 1 to the result. 5) If the the final result is equal to the size of the set then in that case we can say that the given array contains contiguous elements. Lets take a example to understand the above procedure. Lets say that after storing the value in the unordered set we have the values inside it from 1 to 10 (1,2,3,4,5,6,7,8,9,10). The actual order inside the unordered set is not like this I have just taken it to for easier understanding. From the example above we can clearly say that the maximum element present in the set is 10 and minimum element present in the set is 1. Subtracting the minimum element from the maximum element we get 9 as the result(10-1=9). Now when we add 1 to the result and compare it with the size of the unordered set then we can say that the they are equal. (9+1=10 which is equal to the size of the unordered set). Hence the function will return True. Now just imagine if one of the element is not present in the unordered set (say 5) then in that case the size of unordered set is 9 then in that case 10 which is final result is not equal to the size of the unordered set. And hence the function will return False. The Implementation of the above method is :- C++ // C++ implementation to check whether the array contains a// set of contiguous integers#include <bits/stdc++.h>using namespace std; // function to check whether the array contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){ // Declaring and Initialising the set simultaneously unordered_set<int> s(arr, arr + n); // Finding the size of the unordered set int set_size = s.size(); // Find maximum and minimum elements. int max = *max_element(arr, arr + n); int min = *min_element(arr, arr + n); int result = max - min + 1; if (result != set_size) return false; return true;} // Driver programint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << "Yes"; else cout << "No"; return 0;}// This code is contributed by Aditya Kumar (adityakumar129) Yes TIME COMPLEXITY :- O(n) SPACE COMPLEXITY :- O(n) Efficient solution using visited array 1) Find the minimum and maximum elements. 2) Create a visited array of size max-min + 1. Initialize this array as false. 3) Traverse the given array and mark visited[arr[i] – min] as true for every element arr[i]. 4) Traverse visited array and return true if all values are true. Else return false. C++ Java Python3 C# Javascript // C++ implementation to// check whether the array// contains a set of// contiguous integers#include <bits/stdc++.h>using namespace std; // function to check// whether the array// contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){ // Find maximum and // minimum elements. int max = *max_element(arr, arr + n); int min = *min_element(arr, arr + n); int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. bool visited[m]; memset(visited, false, sizeof(visited)); // Mark elements as true. for (int i=0; i<n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i=0; i<m; i++) if (visited[i] == false) return false; return true;} // Driver programint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation to// check whether the array// contains a set of// contiguous integersimport java.util.*; class GFG { // function to check // whether the array // contains a set of // contiguous integers static boolean areElementsContiguous(int arr[], int n) { // Find maximum and // minimum elements. int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i]); min = Math.min(min, arr[i]); } int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. boolean visited[] = new boolean[n]; // Mark elements as true. for (int i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i = 0; i < m; i++) if (visited[i] == false) return false; return true; } /* Driver program */ public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println("Yes"); else System.out.println("No"); }} # Python3 implementation to# check whether the array# contains a set of# contiguous integers # function to check# whether the array# contains a set of# contiguous integersdef areElementsContiguous(arr, n): # Find maximum and # minimum elements. max1 = max(arr) min1 = min(arr) m = max1 - min1 + 1 # There should be at least # m elements in array to # make them contiguous. if (m > n): return False # Create a visited array # and initialize false visited = [0] * m # Mark elements as true. for i in range(0,n) : visited[arr[i] - min1] = True # If any element is not # marked, all elements # are not contiguous. for i in range(0, m): if (visited[i] == False): return False return True # Driver programarr = [5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr) if (areElementsContiguous(arr, n)): print("Yes")else: print("No") # This code is contributed by Smitha Dinesh Semwal // C# implementation to check whether// the array contains a set of// contiguous integersusing System; class GFG { // function to check whether the // array contains a set of // contiguous integers static bool areElementsContiguous( int []arr, int n) { // Find maximum and // minimum elements. int max = int.MinValue; int min = int.MaxValue; for(int i = 0; i < n; i++) { max = Math.Max(max, arr[i]); min = Math.Min(min, arr[i]); } int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. bool []visited = new bool[n]; // Mark elements as true. for (int i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i = 0; i < m; i++) if (visited[i] == false) return false; return true; } /* Driver program */ public static void Main() { int []arr = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.Length; if (areElementsContiguous(arr, n)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by nitin mittal. <script> // Javascript implementation to // check whether the array // contains a set of // contiguous integers // function to check whether the // array contains a set of // contiguous integers function areElementsContiguous(arr, n) { // Find maximum and // minimum elements. let max = Number.MIN_VALUE; let min = Number.MAX_VALUE; for(let i = 0; i < n; i++) { max = Math.max(max, arr[i]); min = Math.min(min, arr[i]); } let m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. let visited = new Array(n); visited.fill(false); // Mark elements as true. for (let i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (let i = 0; i < m; i++) if (visited[i] == false) return false; return true; } let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]; let n = arr.length; if (areElementsContiguous(arr, n)) document.write("Yes"); else document.write("No"); </script> Output: Yes Time Complexity: O(n) Efficient solution using the hash table Insert all the elements in the hash table. Now pick the first element and keep on incrementing in its value by 1 till you find a value not present in the hash table. Again pick the first element and keep on decrementing in its value by 1 till you find a value not present in the hash table. Get the count of elements (obtained by this process) that are present in the hash table. If the count equals hash size print “Yes” else “No”. C++ Java Python C# Javascript // C++ implementation to check whether the array// contains a set of contiguous integers#include <bits/stdc++.h>using namespace std; // Function to check whether the array contains// a set of contiguous integersbool areElementsContiguous(int arr[], int n){ // Storing elements of 'arr[]' in a hash // table 'us' unordered_set<int> us; for (int i = 0; i < n; i++) us.insert(arr[i]); // as arr[0] is present in 'us' int count = 1; // starting with previous smaller element // of arr[0] int curr_ele = arr[0] - 1; // if 'curr_ele' is present in 'us' while (us.find(curr_ele) != us.end()) { // increment count count++; // update 'curr_ele" curr_ele--; } // starting with next greater element // of arr[0] curr_ele = arr[0] + 1; // if 'curr_ele' is present in 'us' while (us.find(curr_ele) != us.end()) { // increment count count++; // update 'curr_ele" curr_ele++; } // returns true if array contains a set of // contiguous integers else returns false return (count == (int)(us.size()));} // Driver program to test aboveint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation to check whether the array// contains a set of contiguous integersimport java.io.*;import java.util.*; class GFG { // Function to check whether the array // contains a set of contiguous integers static Boolean areElementsContiguous(int arr[], int n) { // Storing elements of 'arr[]' in // a hash table 'us' HashSet<Integer> us = new HashSet<Integer>(); for (int i = 0; i < n; i++) us.add(arr[i]); // As arr[0] is present in 'us' int count = 1; // Starting with previous smaller // element of arr[0] int curr_ele = arr[0] - 1; // If 'curr_ele' is present in 'us' while (us.contains(curr_ele) == true) { // increment count count++; // update 'curr_ele" curr_ele--; } // Starting with next greater // element of arr[0] curr_ele = arr[0] + 1; // If 'curr_ele' is present in 'us' while (us.contains(curr_ele) == true) { // increment count count++; // update 'curr_ele" curr_ele++; } // Returns true if array contains a set of // contiguous integers else returns false return (count == (us.size())); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by 'Gitanjali'. # Python implementation to check whether the array# contains a set of contiguous integers # Function to check whether the array# contains a set of contiguous integersdef areElementsContiguous(arr): # Storing elements of 'arr[]' in a hash table 'us' us = set() for i in arr: us.add(i) # As arr[0] is present in 'us' count = 1 # Starting with previous smaller element of arr[0] curr_ele = arr[0] - 1 # If 'curr_ele' is present in 'us' while curr_ele in us: # Increment count count += 1 # Update 'curr_ele" curr_ele -= 1 # Starting with next greater element of arr[0] curr_ele = arr[0] + 1 # If 'curr_ele' is present in 'us' while curr_ele in us: # Increment count count += 1 # Update 'curr_ele" curr_ele += 1 # Returns true if array contains a set of # contiguous integers else returns false return (count == len(us)) # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]if areElementsContiguous(arr): print("Yes")else: print("No") # This code is contributed by 'Ansu Kumari' using System;using System.Collections.Generic; // c# implementation to check whether the array// contains a set of contiguous integers public class GFG{ // Function to check whether the array // contains a set of contiguous integers public static bool? areElementsContiguous(int[] arr, int n) { // Storing elements of 'arr[]' in // a hash table 'us' HashSet<int> us = new HashSet<int>(); for (int i = 0; i < n; i++) { us.Add(arr[i]); } // As arr[0] is present in 'us' int count = 1; // Starting with previous smaller // element of arr[0] int curr_ele = arr[0] - 1; // If 'curr_ele' is present in 'us' while (us.Contains(curr_ele) == true) { // increment count count++; // update 'curr_ele" curr_ele--; } // Starting with next greater // element of arr[0] curr_ele = arr[0] + 1; // If 'curr_ele' is present in 'us' while (us.Contains(curr_ele) == true) { // increment count count++; // update 'curr_ele" curr_ele++; } // Returns true if array contains a set of // contiguous integers else returns false return (count == (us.Count)); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {5, 2, 3, 6, 4, 4, 6, 6}; int n = arr.Length; if (areElementsContiguous(arr, n).Value) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }} // This code is contributed by Shrikant13 <script> // Javascript implementation to check whether the array// contains a set of contiguous integers // Function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous(arr, n){ // Storing elements of 'arr[]' in a hash // table 'us' var us = new Set(); for (var i = 0; i < n; i++) us.add(arr[i]); // as arr[0] is present in 'us' var count = 1; // starting with previous smaller element // of arr[0] var curr_ele = arr[0] - 1; // if 'curr_ele' is present in 'us' while (us.has(curr_ele)) { // increment count count++; // update 'curr_ele" curr_ele--; } // starting with next greater element // of arr[0] curr_ele = arr[0] + 1; // if 'curr_ele' is present in 'us' while (us.has(curr_ele)) { // increment count count++; // update 'curr_ele" curr_ele++; } // returns true if array contains a set of // contiguous integers else returns false return (count == (us.size));} // Driver program to test abovevar arr = [5, 2, 3, 6, 4, 4, 6, 6];var n = arr.length;if (areElementsContiguous(arr, n)) document.write( "Yes");else document.write( "No"); // This code is contributed by rutvik_56.</script> Output : Yes Time Complexity: O(n). Auxiliary Space: O(n). This method requires only one traversal of the given array. It traverses the hash table after array traversal (the hash table contains only distinct elements). nitin mittal shrikanth13 jit_t rameshtravel07 divyeshrabadiya07 rutvik_56 sweetyty surinderdawra388 adityakumar129 simmytarika5 Amazon java-hashset Arrays Hash Sorting Amazon Arrays Hash Sorting 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 Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 419, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses" }, { "code": null, "e": 600, "s": 419, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 685, "s": 600, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 702, "s": 685, "text": "DSA Live Classes" }, { "code": null, "e": 716, "s": 702, "text": "System Design" }, { "code": null, "e": 741, "s": 716, "text": "Java Backend Development" }, { "code": null, "e": 757, "s": 741, "text": "Full Stack LIVE" }, { "code": null, "e": 770, "s": 757, "text": "Explore More" }, { "code": null, "e": 842, "s": 770, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 858, "s": 842, "text": "DSA- Self Paced" }, { "code": null, "e": 869, "s": 858, "text": "SDE Theory" }, { "code": null, "e": 894, "s": 869, "text": "Must-Do Coding Questions" }, { "code": null, "e": 907, "s": 894, "text": "Explore More" }, { "code": null, "e": 1054, "s": 907, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1130, "s": 1054, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1154, "s": 1130, "text": "Competitive Programming" }, { "code": null, "e": 1179, "s": 1154, "text": "Data Structures with C++" }, { "code": null, "e": 1192, "s": 1179, "text": "Data Science" }, { "code": null, "e": 1205, "s": 1192, "text": "Explore More" }, { "code": null, "e": 1265, "s": 1205, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1281, "s": 1265, "text": "DSA- Self Paced" }, { "code": null, "e": 1285, "s": 1281, "text": "CIP" }, { "code": null, "e": 1305, "s": 1285, "text": "JAVA / Python / C++" }, { "code": null, "e": 1318, "s": 1305, "text": "Explore More" }, { "code": null, "e": 1393, "s": 1318, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more" }, { "code": null, "e": 1406, "s": 1393, "text": "School Guide" }, { "code": null, "e": 1425, "s": 1406, "text": "Python Programming" }, { "code": null, "e": 1444, "s": 1425, "text": "Learn To Make Apps" }, { "code": null, "e": 1457, "s": 1444, "text": "Explore more" }, { "code": null, "e": 1469, "s": 1457, "text": "All Courses" }, { "code": null, "e": 4036, "s": 1469, "text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 4103, "s": 4036, "text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise" }, { "code": null, "e": 4121, "s": 4103, "text": "Must Do Questions" }, { "code": null, "e": 4136, "s": 4121, "text": "DSA Topic-wise" }, { "code": null, "e": 4153, "s": 4136, "text": "DSA Company-wise" }, { "code": null, "e": 4734, "s": 4153, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 5067, "s": 4734, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 5087, "s": 5067, "text": "Asymptotic Analysis" }, { "code": null, "e": 5117, "s": 5087, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 5138, "s": 5117, "text": "Asymptotic Notations" }, { "code": null, "e": 5174, "s": 5138, "text": "Little o and little omega notations" }, { "code": null, "e": 5203, "s": 5174, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5221, "s": 5203, "text": "Analysis of Loops" }, { "code": null, "e": 5241, "s": 5221, "text": "Solving Recurrences" }, { "code": null, "e": 5260, "s": 5241, "text": "Amortized Analysis" }, { "code": null, "e": 5296, "s": 5260, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5325, "s": 5296, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5362, "s": 5325, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5389, "s": 5362, "text": "A Time Complexity Question" }, { "code": null, "e": 5410, "s": 5389, "text": "Searching Algorithms" }, { "code": null, "e": 5429, "s": 5410, "text": "Sorting Algorithms" }, { "code": null, "e": 5446, "s": 5429, "text": "Graph Algorithms" }, { "code": null, "e": 5464, "s": 5446, "text": "Pattern Searching" }, { "code": null, "e": 5485, "s": 5464, "text": "Geometric Algorithms" }, { "code": null, "e": 5498, "s": 5485, "text": "Mathematical" }, { "code": null, "e": 5517, "s": 5498, "text": "Bitwise Algorithms" }, { "code": null, "e": 5539, "s": 5517, "text": "Randomized Algorithms" }, { "code": null, "e": 5557, "s": 5539, "text": "Greedy Algorithms" }, { "code": null, "e": 5577, "s": 5557, "text": "Dynamic Programming" }, { "code": null, "e": 5596, "s": 5577, "text": "Divide and Conquer" }, { "code": null, "e": 5609, "s": 5596, "text": "Backtracking" }, { "code": null, "e": 5626, "s": 5609, "text": "Branch and Bound" }, { "code": null, "e": 5641, "s": 5626, "text": "All Algorithms" }, { "code": null, "e": 5784, "s": 5641, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5791, "s": 5784, "text": "Arrays" }, { "code": null, "e": 5803, "s": 5791, "text": "Linked List" }, { "code": null, "e": 5809, "s": 5803, "text": "Stack" }, { "code": null, "e": 5815, "s": 5809, "text": "Queue" }, { "code": null, "e": 5827, "s": 5815, "text": "Binary Tree" }, { "code": null, "e": 5846, "s": 5827, "text": "Binary Search Tree" }, { "code": null, "e": 5851, "s": 5846, "text": "Heap" }, { "code": null, "e": 5859, "s": 5851, "text": "Hashing" }, { "code": null, "e": 5865, "s": 5859, "text": "Graph" }, { "code": null, "e": 5889, "s": 5865, "text": "Advanced Data Structure" }, { "code": null, "e": 5896, "s": 5889, "text": "Matrix" }, { "code": null, "e": 5904, "s": 5896, "text": "Strings" }, { "code": null, "e": 5924, "s": 5904, "text": "All Data Structures" }, { "code": null, "e": 6144, "s": 5924, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 6164, "s": 6144, "text": "Company Preparation" }, { "code": null, "e": 6175, "s": 6164, "text": "Top Topics" }, { "code": null, "e": 6202, "s": 6175, "text": "Practice Company Questions" }, { "code": null, "e": 6224, "s": 6202, "text": "Interview Experiences" }, { "code": null, "e": 6247, "s": 6224, "text": "Experienced Interviews" }, { "code": null, "e": 6269, "s": 6247, "text": "Internship Interviews" }, { "code": null, "e": 6294, "s": 6269, "text": "Competititve Programming" }, { "code": null, "e": 6310, "s": 6294, "text": "Design Patterns" }, { "code": null, "e": 6333, "s": 6310, "text": "System Design Tutorial" }, { "code": null, "e": 6357, "s": 6333, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6438, "s": 6357, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6440, "s": 6438, "text": "C" }, { "code": null, "e": 6444, "s": 6440, "text": "C++" }, { "code": null, "e": 6449, "s": 6444, "text": "Java" }, { "code": null, "e": 6456, "s": 6449, "text": "Python" }, { "code": null, "e": 6459, "s": 6456, "text": "C#" }, { "code": null, "e": 6470, "s": 6459, "text": "JavaScript" }, { "code": null, "e": 6477, "s": 6470, "text": "jQuery" }, { "code": null, "e": 6481, "s": 6477, "text": "SQL" }, { "code": null, "e": 6485, "s": 6481, "text": "PHP" }, { "code": null, "e": 6491, "s": 6485, "text": "Scala" }, { "code": null, "e": 6496, "s": 6491, "text": "Perl" }, { "code": null, "e": 6508, "s": 6496, "text": "Go Language" }, { "code": null, "e": 6513, "s": 6508, "text": "HTML" }, { "code": null, "e": 6517, "s": 6513, "text": "CSS" }, { "code": null, "e": 6524, "s": 6517, "text": "Kotlin" }, { "code": null, "e": 6570, "s": 6524, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6587, "s": 6570, "text": "Machine Learning" }, { "code": null, "e": 6600, "s": 6587, "text": "Data Science" }, { "code": null, "e": 6767, "s": 6600, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6779, "s": 6767, "text": "Mathematics" }, { "code": null, "e": 6796, "s": 6779, "text": "Operating System" }, { "code": null, "e": 6801, "s": 6796, "text": "DBMS" }, { "code": null, "e": 6819, "s": 6801, "text": "Computer Networks" }, { "code": null, "e": 6858, "s": 6819, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6880, "s": 6858, "text": "Theory of Computation" }, { "code": null, "e": 6896, "s": 6880, "text": "Compiler Design" }, { "code": null, "e": 6910, "s": 6896, "text": "Digital Logic" }, { "code": null, "e": 6931, "s": 6910, "text": "Software Engineering" }, { "code": null, "e": 7106, "s": 6931, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 7134, "s": 7106, "text": "GATE Computer Science Notes" }, { "code": null, "e": 7152, "s": 7134, "text": "Last Minute Notes" }, { "code": null, "e": 7174, "s": 7152, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7216, "s": 7174, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7232, "s": 7216, "text": "GATE 2021 Dates" }, { "code": null, "e": 7254, "s": 7232, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7283, "s": 7254, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7357, "s": 7283, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7362, "s": 7357, "text": "HTML" }, { "code": null, "e": 7366, "s": 7362, "text": "CSS" }, { "code": null, "e": 7377, "s": 7366, "text": "JavaScript" }, { "code": null, "e": 7387, "s": 7377, "text": "AngularJS" }, { "code": null, "e": 7395, "s": 7387, "text": "ReactJS" }, { "code": null, "e": 7402, "s": 7395, "text": "NodeJS" }, { "code": null, "e": 7412, "s": 7402, "text": "Bootstrap" }, { "code": null, "e": 7419, "s": 7412, "text": "jQuery" }, { "code": null, "e": 7423, "s": 7419, "text": "PHP" }, { "code": null, "e": 7486, "s": 7423, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7511, "s": 7486, "text": "Software Design Patterns" }, { "code": null, "e": 7534, "s": 7511, "text": "System Design Tutorial" }, { "code": null, "e": 8091, "s": 7534, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8110, "s": 8091, "text": "School Programming" }, { "code": null, "e": 8202, "s": 8110, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8216, "s": 8202, "text": "Number System" }, { "code": null, "e": 8224, "s": 8216, "text": "Algebra" }, { "code": null, "e": 8237, "s": 8224, "text": "Trigonometry" }, { "code": null, "e": 8248, "s": 8237, "text": "Statistics" }, { "code": null, "e": 8260, "s": 8248, "text": "Probability" }, { "code": null, "e": 8269, "s": 8260, "text": "Geometry" }, { "code": null, "e": 8281, "s": 8269, "text": "Mensuration" }, { "code": null, "e": 8290, "s": 8281, "text": "Calculus" }, { "code": null, "e": 8383, "s": 8290, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8397, "s": 8383, "text": "Class 8 Notes" }, { "code": null, "e": 8411, "s": 8397, "text": "Class 9 Notes" }, { "code": null, "e": 8426, "s": 8411, "text": "Class 10 Notes" }, { "code": null, "e": 8441, "s": 8426, "text": "Class 11 Notes" }, { "code": null, "e": 8456, "s": 8441, "text": "Class 12 Notes" }, { "code": null, "e": 8585, "s": 8456, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8608, "s": 8585, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8631, "s": 8608, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8655, "s": 8631, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8679, "s": 8655, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8703, "s": 8679, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8836, "s": 8703, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8859, "s": 8836, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8882, "s": 8859, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8906, "s": 8882, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8930, "s": 8906, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8954, "s": 8930, "text": "Class 12 Maths Solution" }, { "code": null, "e": 9035, "s": 8954, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 9049, "s": 9035, "text": "Class 8 Notes" }, { "code": null, "e": 9063, "s": 9049, "text": "Class 9 Notes" }, { "code": null, "e": 9078, "s": 9063, "text": "Class 10 Notes" }, { "code": null, "e": 9093, "s": 9078, "text": "Class 11 Notes" }, { "code": null, "e": 9299, "s": 9093, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9410, "s": 9299, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9452, "s": 9410, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9474, "s": 9452, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9519, "s": 9474, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9602, "s": 9519, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9628, "s": 9602, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9655, "s": 9628, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9680, "s": 9655, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9870, "s": 9680, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 9896, "s": 9870, "text": "Campus Ambassador Program" }, { "code": null, "e": 9922, "s": 9896, "text": "School Ambassador Program" }, { "code": null, "e": 9930, "s": 9922, "text": "Project" }, { "code": null, "e": 9948, "s": 9930, "text": "Geek of the Month" }, { "code": null, "e": 9973, "s": 9948, "text": "Campus Geek of the Month" }, { "code": null, "e": 9990, "s": 9973, "text": "Placement Course" }, { "code": null, "e": 10015, "s": 9990, "text": "Competititve Programming" }, { "code": null, "e": 10028, "s": 10015, "text": "Testimonials" }, { "code": null, "e": 10044, "s": 10028, "text": "Geek on the Top" }, { "code": null, "e": 10052, "s": 10044, "text": "Careers" }, { "code": null, "e": 10063, "s": 10052, "text": "Internship" }, { "code": null, "e": 10102, "s": 10063, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 10117, "s": 10102, "text": "Apply for Jobs" }, { "code": null, "e": 10128, "s": 10117, "text": "Post a Job" }, { "code": null, "e": 10139, "s": 10128, "text": "JOB-A-THON" }, { "code": null, "e": 10146, "s": 10139, "text": "Events" }, { "code": null, "e": 10417, "s": 10150, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10430, "s": 10417, "text": "Geeks Digest" }, { "code": null, "e": 10438, "s": 10430, "text": "Quizzes" }, { "code": null, "e": 10451, "s": 10438, "text": "Geeks Campus" }, { "code": null, "e": 10466, "s": 10451, "text": "Gblog Articles" }, { "code": null, "e": 10470, "s": 10466, "text": "IDE" }, { "code": null, "e": 10484, "s": 10470, "text": "Campus Mantri" }, { "code": null, "e": 10492, "s": 10484, "text": "Sign In" }, { "code": null, "e": 10500, "s": 10492, "text": "Sign In" }, { "code": null, "e": 10505, "s": 10500, "text": "Home" }, { "code": null, "e": 10518, "s": 10505, "text": "Saved Videos" }, { "code": null, "e": 10526, "s": 10518, "text": "Courses" }, { "code": null, "e": 14731, "s": 10526, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 14785, "s": 14731, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 14908, "s": 14785, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 14927, "s": 14908, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 14943, "s": 14927, "text": "\nSystem Design\n" }, { "code": null, "e": 14970, "s": 14943, "text": "\nJava Backend Development\n" }, { "code": null, "e": 14988, "s": 14970, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15003, "s": 14988, "text": "\nExplore More\n" }, { "code": null, "e": 15111, "s": 15003, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15129, "s": 15111, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15142, "s": 15129, "text": "\nSDE Theory\n" }, { "code": null, "e": 15169, "s": 15142, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15184, "s": 15169, "text": "\nExplore More\n" }, { "code": null, "e": 15225, "s": 15184, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 15337, "s": 15225, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 15363, "s": 15337, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 15390, "s": 15363, "text": "\nData Structures with C++\n" }, { "code": null, "e": 15405, "s": 15390, "text": "\nData Science\n" }, { "code": null, "e": 15420, "s": 15405, "text": "\nExplore More\n" }, { "code": null, "e": 15516, "s": 15420, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 15534, "s": 15516, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15540, "s": 15534, "text": "\nCIP\n" }, { "code": null, "e": 15562, "s": 15540, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 15577, "s": 15562, "text": "\nExplore More\n" }, { "code": null, "e": 15688, "s": 15577, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 15703, "s": 15688, "text": "\nSchool Guide\n" }, { "code": null, "e": 15724, "s": 15703, "text": "\nPython Programming\n" }, { "code": null, "e": 15745, "s": 15724, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 15760, "s": 15745, "text": "\nExplore more\n" }, { "code": null, "e": 15861, "s": 15760, "text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n" }, { "code": null, "e": 15881, "s": 15861, "text": "\nMust Do Questions\n" }, { "code": null, "e": 15898, "s": 15881, "text": "\nDSA Topic-wise\n" }, { "code": null, "e": 15917, "s": 15898, "text": "\nDSA Company-wise\n" }, { "code": null, "e": 16222, "s": 15917, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16245, "s": 16222, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16266, "s": 16245, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16285, "s": 16266, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16305, "s": 16285, "text": "\nPattern Searching\n" }, { "code": null, "e": 16328, "s": 16305, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16343, "s": 16328, "text": "\nMathematical\n" }, { "code": null, "e": 16364, "s": 16343, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16388, "s": 16364, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 16408, "s": 16388, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 16430, "s": 16408, "text": "\nDynamic Programming\n" }, { "code": null, "e": 16451, "s": 16430, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 16466, "s": 16451, "text": "\nBacktracking\n" }, { "code": null, "e": 16485, "s": 16466, "text": "\nBranch and Bound\n" }, { "code": null, "e": 16502, "s": 16485, "text": "\nAll Algorithms\n" }, { "code": null, "e": 16887, "s": 16502, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 16909, "s": 16887, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 16941, "s": 16909, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 16964, "s": 16941, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17002, "s": 16964, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17033, "s": 17002, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17053, "s": 17033, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17075, "s": 17053, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17096, "s": 17075, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17134, "s": 17096, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17165, "s": 17134, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17204, "s": 17165, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17233, "s": 17204, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 17430, "s": 17233, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 17439, "s": 17430, "text": "\nArrays\n" }, { "code": null, "e": 17453, "s": 17439, "text": "\nLinked List\n" }, { "code": null, "e": 17461, "s": 17453, "text": "\nStack\n" }, { "code": null, "e": 17469, "s": 17461, "text": "\nQueue\n" }, { "code": null, "e": 17483, "s": 17469, "text": "\nBinary Tree\n" }, { "code": null, "e": 17504, "s": 17483, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 17511, "s": 17504, "text": "\nHeap\n" }, { "code": null, "e": 17521, "s": 17511, "text": "\nHashing\n" }, { "code": null, "e": 17529, "s": 17521, "text": "\nGraph\n" }, { "code": null, "e": 17555, "s": 17529, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 17564, "s": 17555, "text": "\nMatrix\n" }, { "code": null, "e": 17574, "s": 17564, "text": "\nStrings\n" }, { "code": null, "e": 17596, "s": 17574, "text": "\nAll Data Structures\n" }, { "code": null, "e": 17864, "s": 17596, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 17886, "s": 17864, "text": "\nCompany Preparation\n" }, { "code": null, "e": 17899, "s": 17886, "text": "\nTop Topics\n" }, { "code": null, "e": 17928, "s": 17899, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 17952, "s": 17928, "text": "\nInterview Experiences\n" }, { "code": null, "e": 17977, "s": 17952, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18001, "s": 17977, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18028, "s": 18001, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18046, "s": 18028, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18071, "s": 18046, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18097, "s": 18071, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18236, "s": 18097, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18240, "s": 18236, "text": "\nC\n" }, { "code": null, "e": 18246, "s": 18240, "text": "\nC++\n" }, { "code": null, "e": 18253, "s": 18246, "text": "\nJava\n" }, { "code": null, "e": 18262, "s": 18253, "text": "\nPython\n" }, { "code": null, "e": 18267, "s": 18262, "text": "\nC#\n" }, { "code": null, "e": 18280, "s": 18267, "text": "\nJavaScript\n" }, { "code": null, "e": 18289, "s": 18280, "text": "\njQuery\n" }, { "code": null, "e": 18295, "s": 18289, "text": "\nSQL\n" }, { "code": null, "e": 18301, "s": 18295, "text": "\nPHP\n" }, { "code": null, "e": 18309, "s": 18301, "text": "\nScala\n" }, { "code": null, "e": 18316, "s": 18309, "text": "\nPerl\n" }, { "code": null, "e": 18330, "s": 18316, "text": "\nGo Language\n" }, { "code": null, "e": 18337, "s": 18330, "text": "\nHTML\n" }, { "code": null, "e": 18343, "s": 18337, "text": "\nCSS\n" }, { "code": null, "e": 18352, "s": 18343, "text": "\nKotlin\n" }, { "code": null, "e": 18430, "s": 18352, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 18449, "s": 18430, "text": "\nMachine Learning\n" }, { "code": null, "e": 18464, "s": 18449, "text": "\nData Science\n" }, { "code": null, "e": 18677, "s": 18464, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 18691, "s": 18677, "text": "\nMathematics\n" }, { "code": null, "e": 18710, "s": 18691, "text": "\nOperating System\n" }, { "code": null, "e": 18717, "s": 18710, "text": "\nDBMS\n" }, { "code": null, "e": 18737, "s": 18717, "text": "\nComputer Networks\n" }, { "code": null, "e": 18778, "s": 18737, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 18802, "s": 18778, "text": "\nTheory of Computation\n" }, { "code": null, "e": 18820, "s": 18802, "text": "\nCompiler Design\n" }, { "code": null, "e": 18836, "s": 18820, "text": "\nDigital Logic\n" }, { "code": null, "e": 18859, "s": 18836, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19076, "s": 18859, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19106, "s": 19076, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19126, "s": 19106, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19150, "s": 19126, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19194, "s": 19150, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19212, "s": 19194, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19236, "s": 19212, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19267, "s": 19236, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19387, "s": 19267, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19394, "s": 19387, "text": "\nHTML\n" }, { "code": null, "e": 19400, "s": 19394, "text": "\nCSS\n" }, { "code": null, "e": 19413, "s": 19400, "text": "\nJavaScript\n" }, { "code": null, "e": 19425, "s": 19413, "text": "\nAngularJS\n" }, { "code": null, "e": 19435, "s": 19425, "text": "\nReactJS\n" }, { "code": null, "e": 19444, "s": 19435, "text": "\nNodeJS\n" }, { "code": null, "e": 19456, "s": 19444, "text": "\nBootstrap\n" }, { "code": null, "e": 19465, "s": 19456, "text": "\njQuery\n" }, { "code": null, "e": 19471, "s": 19465, "text": "\nPHP\n" }, { "code": null, "e": 19566, "s": 19471, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 19593, "s": 19566, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 19618, "s": 19593, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 19682, "s": 19618, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 19703, "s": 19682, "text": "\nSchool Programming\n" }, { "code": null, "e": 19839, "s": 19703, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 19855, "s": 19839, "text": "\nNumber System\n" }, { "code": null, "e": 19865, "s": 19855, "text": "\nAlgebra\n" }, { "code": null, "e": 19880, "s": 19865, "text": "\nTrigonometry\n" }, { "code": null, "e": 19893, "s": 19880, "text": "\nStatistics\n" }, { "code": null, "e": 19907, "s": 19893, "text": "\nProbability\n" }, { "code": null, "e": 19918, "s": 19907, "text": "\nGeometry\n" }, { "code": null, "e": 19932, "s": 19918, "text": "\nMensuration\n" }, { "code": null, "e": 19943, "s": 19932, "text": "\nCalculus\n" }, { "code": null, "e": 20074, "s": 19943, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20090, "s": 20074, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20106, "s": 20090, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20123, "s": 20106, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20140, "s": 20123, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20157, "s": 20140, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20324, "s": 20157, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20349, "s": 20324, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20374, "s": 20349, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20400, "s": 20374, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20426, "s": 20400, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20452, "s": 20426, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20623, "s": 20452, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20648, "s": 20623, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20673, "s": 20648, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20699, "s": 20673, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20725, "s": 20699, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20751, "s": 20725, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20868, "s": 20751, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 20884, "s": 20868, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20900, "s": 20884, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20917, "s": 20900, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20934, "s": 20917, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20976, "s": 20934, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21121, "s": 20976, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21165, "s": 21121, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21189, "s": 21165, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21236, "s": 21189, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21353, "s": 21236, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21381, "s": 21353, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 21410, "s": 21381, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 21437, "s": 21410, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21677, "s": 21437, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n" }, { "code": null, "e": 21705, "s": 21677, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 21733, "s": 21705, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 21743, "s": 21733, "text": "\nProject\n" }, { "code": null, "e": 21763, "s": 21743, "text": "\nGeek of the Month\n" }, { "code": null, "e": 21790, "s": 21763, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 21809, "s": 21790, "text": "\nPlacement Course\n" }, { "code": null, "e": 21836, "s": 21809, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 21851, "s": 21836, "text": "\nTestimonials\n" }, { "code": null, "e": 21869, "s": 21851, "text": "\nGeek on the Top\n" }, { "code": null, "e": 21879, "s": 21869, "text": "\nCareers\n" }, { "code": null, "e": 21892, "s": 21879, "text": "\nInternship\n" }, { "code": null, "e": 21930, "s": 21892, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22003, "s": 21930, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22020, "s": 22003, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22033, "s": 22020, "text": "\nPost a Job\n" }, { "code": null, "e": 22046, "s": 22033, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 22052, "s": 22046, "text": "GBlog" }, { "code": null, "e": 22060, "s": 22052, "text": "Puzzles" }, { "code": null, "e": 22073, "s": 22060, "text": "What's New ?" }, { "code": null, "e": 22079, "s": 22073, "text": "Array" }, { "code": null, "e": 22086, "s": 22079, "text": "Matrix" }, { "code": null, "e": 22094, "s": 22086, "text": "Strings" }, { "code": null, "e": 22102, "s": 22094, "text": "Hashing" }, { "code": null, "e": 22114, "s": 22102, "text": "Linked List" }, { "code": null, "e": 22120, "s": 22114, "text": "Stack" }, { "code": null, "e": 22126, "s": 22120, "text": "Queue" }, { "code": null, "e": 22138, "s": 22126, "text": "Binary Tree" }, { "code": null, "e": 22157, "s": 22138, "text": "Binary Search Tree" }, { "code": null, "e": 22162, "s": 22157, "text": "Heap" }, { "code": null, "e": 22168, "s": 22162, "text": "Graph" }, { "code": null, "e": 22178, "s": 22168, "text": "Searching" }, { "code": null, "e": 22186, "s": 22178, "text": "Sorting" }, { "code": null, "e": 22203, "s": 22186, "text": "Divide & Conquer" }, { "code": null, "e": 22216, "s": 22203, "text": "Mathematical" }, { "code": null, "e": 22226, "s": 22216, "text": "Geometric" }, { "code": null, "e": 22234, "s": 22226, "text": "Bitwise" }, { "code": null, "e": 22241, "s": 22234, "text": "Greedy" }, { "code": null, "e": 22254, "s": 22241, "text": "Backtracking" }, { "code": null, "e": 22271, "s": 22254, "text": "Branch and Bound" }, { "code": null, "e": 22291, "s": 22271, "text": "Dynamic Programming" }, { "code": null, "e": 22309, "s": 22291, "text": "Pattern Searching" }, { "code": null, "e": 22320, "s": 22309, "text": "Randomized" }, { "code": null, "e": 22388, "s": 22320, "text": "Check if array contains contiguous integers with duplicates allowed" }, { "code": null, "e": 22445, "s": 22388, "text": "Check if array elements are consecutive | Added Method 4" }, { "code": null, "e": 22478, "s": 22445, "text": "Find the smallest missing number" }, { "code": null, "e": 22537, "s": 22478, "text": "Maximum sum such that no two elements are adjacent | Set 2" }, { "code": null, "e": 22588, "s": 22537, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 22635, "s": 22588, "text": "Find maximum possible stolen value from houses" }, { "code": null, "e": 22696, "s": 22635, "text": "Find number of solutions of a linear equation of n variables" }, { "code": null, "e": 22750, "s": 22696, "text": "Count number of ways to reach a given score in a game" }, { "code": null, "e": 22780, "s": 22750, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 22811, "s": 22780, "text": "Program for nth Catalan Number" }, { "code": null, "e": 22860, "s": 22811, "text": "Bell Numbers (Number of ways to Partition a Set)" }, { "code": null, "e": 22888, "s": 22860, "text": "Binomial Coefficient | DP-9" }, { "code": null, "e": 22912, "s": 22888, "text": "Permutation Coefficient" }, { "code": null, "e": 22927, "s": 22912, "text": "Tiling Problem" }, { "code": null, "e": 22945, "s": 22927, "text": "Gold Mine Problem" }, { "code": null, "e": 22964, "s": 22945, "text": "Coin Change | DP-7" }, { "code": null, "e": 23017, "s": 22964, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 23066, "s": 23017, "text": "Greedy Algorithm to find Minimum number of Coins" }, { "code": null, "e": 23123, "s": 23066, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 23186, "s": 23123, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 23227, "s": 23186, "text": "Reverse an array in groups of given size" }, { "code": null, "e": 23283, "s": 23227, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 23362, "s": 23283, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 23443, "s": 23362, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)" }, { "code": null, "e": 23483, "s": 23443, "text": "K’th Smallest/Largest Element using STL" }, { "code": null, "e": 23498, "s": 23483, "text": "Arrays in Java" }, { "code": null, "e": 23544, "s": 23498, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23576, "s": 23544, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 23603, "s": 23576, "text": "Program for array rotation" }, { "code": null, "e": 23619, "s": 23603, "text": "Arrays in C/C++" }, { "code": null, "e": 23687, "s": 23619, "text": "Check if array contains contiguous integers with duplicates allowed" }, { "code": null, "e": 23744, "s": 23687, "text": "Check if array elements are consecutive | Added Method 4" }, { "code": null, "e": 23777, "s": 23744, "text": "Find the smallest missing number" }, { "code": null, "e": 23836, "s": 23777, "text": "Maximum sum such that no two elements are adjacent | Set 2" }, { "code": null, "e": 23887, "s": 23836, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 23934, "s": 23887, "text": "Find maximum possible stolen value from houses" }, { "code": null, "e": 23995, "s": 23934, "text": "Find number of solutions of a linear equation of n variables" }, { "code": null, "e": 24049, "s": 23995, "text": "Count number of ways to reach a given score in a game" }, { "code": null, "e": 24079, "s": 24049, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 24110, "s": 24079, "text": "Program for nth Catalan Number" }, { "code": null, "e": 24159, "s": 24110, "text": "Bell Numbers (Number of ways to Partition a Set)" }, { "code": null, "e": 24187, "s": 24159, "text": "Binomial Coefficient | DP-9" }, { "code": null, "e": 24211, "s": 24187, "text": "Permutation Coefficient" }, { "code": null, "e": 24226, "s": 24211, "text": "Tiling Problem" }, { "code": null, "e": 24244, "s": 24226, "text": "Gold Mine Problem" }, { "code": null, "e": 24263, "s": 24244, "text": "Coin Change | DP-7" }, { "code": null, "e": 24316, "s": 24263, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 24365, "s": 24316, "text": "Greedy Algorithm to find Minimum number of Coins" }, { "code": null, "e": 24422, "s": 24365, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 24485, "s": 24422, "text": "Minimum Number of Platforms Required for a Railway/Bus Station" }, { "code": null, "e": 24526, "s": 24485, "text": "Reverse an array in groups of given size" }, { "code": null, "e": 24582, "s": 24526, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 24661, "s": 24582, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)" }, { "code": null, "e": 24742, "s": 24661, "text": "K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)" }, { "code": null, "e": 24782, "s": 24742, "text": "K’th Smallest/Largest Element using STL" }, { "code": null, "e": 24797, "s": 24782, "text": "Arrays in Java" }, { "code": null, "e": 24843, "s": 24797, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24875, "s": 24843, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24902, "s": 24875, "text": "Program for array rotation" }, { "code": null, "e": 24918, "s": 24902, "text": "Arrays in C/C++" }, { "code": null, "e": 24942, "s": 24918, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 25059, "s": 24942, "text": "Given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous integers else print “No”." }, { "code": null, "e": 25071, "s": 25059, "text": "Examples: " }, { "code": null, "e": 25256, "s": 25071, "text": "Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6}\nOutput : Yes\nThe elements form a contiguous set of integers\nwhich is {2, 3, 4, 5, 6}.\n\nInput : arr[] = {10, 14, 10, 12, 12, 13, 15}\nOutput : No" }, { "code": null, "e": 25506, "s": 25256, "text": "We have discussed different solutions for distinct elements in the below post. Check if array elements are consecutiveA simple solution is to first sort the array. Then traverse the array to check if all consecutive elements differ at most by one. " }, { "code": null, "e": 25508, "s": 25506, "text": "C" }, { "code": null, "e": 25513, "s": 25508, "text": "Java" }, { "code": null, "e": 25521, "s": 25513, "text": "Python3" }, { "code": null, "e": 25524, "s": 25521, "text": "C#" }, { "code": null, "e": 25528, "s": 25524, "text": "PHP" }, { "code": null, "e": 25539, "s": 25528, "text": "Javascript" }, { "code": "// Sorting based C++ implementation// to check whether the array// contains a set of contiguous// integers#include <bits/stdc++.h>using namespace std; // function to check whether// the array contains a set// of contiguous integersbool areElementsContiguous(int arr[], int n){ // Sort the array sort(arr, arr+n); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i-1] > 1) return false; return true;} // Driver program to test aboveint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 26351, "s": 25539, "text": null }, { "code": "// Sorting based Java implementation// to check whether the array// contains a set of contiguous// integersimport java.util.*; class GFG { // function to check whether // the array contains a set // of contiguous integers static boolean areElementsContiguous(int arr[], int n) { // Sort the array Arrays.sort(arr); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i-1] > 1) return false; return true; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } } // This code is contributed by Arnav Kr. Mandal. ", "e": 27414, "s": 26351, "text": null }, { "code": "# Sorting based Python implementation# to check whether the array# contains a set of contiguous integers def areElementsContiguous(arr, n): # Sort the array arr.sort() # After sorting, check if # current element is either # same as previous or is # one more. for i in range(1,n): if (arr[i] - arr[i-1] > 1) : return 0 return 1 # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr)if areElementsContiguous(arr, n): print(\"Yes\")else: print(\"No\") # This code is contributed by 'Ansu Kumari'.", "e": 27954, "s": 27414, "text": null }, { "code": "// Sorting based C# implementation// to check whether the array// contains a set of contiguous// integersusing System; class GFG { // function to check whether // the array contains a set // of contiguous integers static bool areElementsContiguous(int []arr, int n) { // Sort the array Array.Sort(arr); // After sorting, check if // current element is either // same as previous or is // one more. for (int i = 1; i < n; i++) if (arr[i] - arr[i - 1] > 1) return false; return true; } // Driver program public static void Main() { int []arr = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.Length; if (areElementsContiguous(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } } // This code is contributed by Vt_m.", "e": 28915, "s": 27954, "text": null }, { "code": "<?php// Sorting based PHP implementation to check// whether the array contains a set of contiguous// integers // function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous($arr, $n){ // Sort the array sort($arr); // After sorting, check if current element // is either same as previous or is one more. for ($i = 1; $i < $n; $i++) if ($arr[$i] - $arr[$i - 1] > 1) return false; return true;} // Driver Code$arr = array( 5, 2, 3, 6, 4, 4, 6, 6 );$n = sizeof($arr); if (areElementsContiguous($arr, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed by ajit?>", "e": 29596, "s": 28915, "text": null }, { "code": "<script> // Sorting based Javascript implementation // to check whether the array // contains a set of contiguous // integers // function to check whether // the array contains a set // of contiguous integers function areElementsContiguous(arr, n) { // Sort the array arr.sort(function(a, b){return a - b}); // After sorting, check if // current element is either // same as previous or is // one more. for (let i = 1; i < n; i++) if (arr[i] - arr[i - 1] > 1) return false; return true; } let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]; let n = arr.length; if (areElementsContiguous(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by rameshtravel07.</script>", "e": 30414, "s": 29596, "text": null }, { "code": null, "e": 30424, "s": 30414, "text": "Output: " }, { "code": null, "e": 30428, "s": 30424, "text": "Yes" }, { "code": null, "e": 30456, "s": 30428, "text": "Time Complexity: O(n Log n)" }, { "code": null, "e": 30480, "s": 30456, "text": "Another Approach is :- " }, { "code": null, "e": 30661, "s": 30480, "text": "if we can find the minimum element and maximum element that are present in the array and use the below procedure then we can say that the array contains contiguous elements or not." }, { "code": null, "e": 30674, "s": 30661, "text": "PROCEDURE :-" }, { "code": null, "e": 30780, "s": 30674, "text": "1) Store the elements in unordered set (So as to maintain the Time complexity of the problem i.e. O(n) ) " }, { "code": null, "e": 30869, "s": 30780, "text": "2) Find the minimum element present in the array and store it in a variable say min_ele." }, { "code": null, "e": 30958, "s": 30869, "text": "3) Find the maximum element present in the array and store it in a variable say max_ele." }, { "code": null, "e": 31077, "s": 30958, "text": "4) Now just think a little bit we can notice that if we Subtract the min_ele from the max_ele and add 1 to the result." }, { "code": null, "e": 31216, "s": 31077, "text": "5) If the the final result is equal to the size of the set then in that case we can say that the given array contains contiguous elements." }, { "code": null, "e": 31271, "s": 31216, "text": "Lets take a example to understand the above procedure." }, { "code": null, "e": 31505, "s": 31271, "text": "Lets say that after storing the value in the unordered set we have the values inside it from 1 to 10 (1,2,3,4,5,6,7,8,9,10). The actual order inside the unordered set is not like this I have just taken it to for easier understanding." }, { "code": null, "e": 31642, "s": 31505, "text": "From the example above we can clearly say that the maximum element present in the set is 10 and minimum element present in the set is 1." }, { "code": null, "e": 31731, "s": 31642, "text": "Subtracting the minimum element from the maximum element we get 9 as the result(10-1=9)." }, { "code": null, "e": 31912, "s": 31731, "text": "Now when we add 1 to the result and compare it with the size of the unordered set then we can say that the they are equal. (9+1=10 which is equal to the size of the unordered set)." }, { "code": null, "e": 31949, "s": 31912, "text": "Hence the function will return True." }, { "code": null, "e": 32213, "s": 31949, "text": "Now just imagine if one of the element is not present in the unordered set (say 5) then in that case the size of unordered set is 9 then in that case 10 which is final result is not equal to the size of the unordered set. And hence the function will return False." }, { "code": null, "e": 32259, "s": 32213, "text": "The Implementation of the above method is :- " }, { "code": null, "e": 32263, "s": 32259, "text": "C++" }, { "code": "// C++ implementation to check whether the array contains a// set of contiguous integers#include <bits/stdc++.h>using namespace std; // function to check whether the array contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){ // Declaring and Initialising the set simultaneously unordered_set<int> s(arr, arr + n); // Finding the size of the unordered set int set_size = s.size(); // Find maximum and minimum elements. int max = *max_element(arr, arr + n); int min = *min_element(arr, arr + n); int result = max - min + 1; if (result != set_size) return false; return true;} // Driver programint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}// This code is contributed by Aditya Kumar (adityakumar129)", "e": 33183, "s": 32263, "text": null }, { "code": null, "e": 33187, "s": 33183, "text": "Yes" }, { "code": null, "e": 33211, "s": 33187, "text": "TIME COMPLEXITY :- O(n)" }, { "code": null, "e": 33236, "s": 33211, "text": "SPACE COMPLEXITY :- O(n)" }, { "code": null, "e": 33575, "s": 33236, "text": "Efficient solution using visited array 1) Find the minimum and maximum elements. 2) Create a visited array of size max-min + 1. Initialize this array as false. 3) Traverse the given array and mark visited[arr[i] – min] as true for every element arr[i]. 4) Traverse visited array and return true if all values are true. Else return false. " }, { "code": null, "e": 33579, "s": 33575, "text": "C++" }, { "code": null, "e": 33584, "s": 33579, "text": "Java" }, { "code": null, "e": 33592, "s": 33584, "text": "Python3" }, { "code": null, "e": 33595, "s": 33592, "text": "C#" }, { "code": null, "e": 33606, "s": 33595, "text": "Javascript" }, { "code": "// C++ implementation to// check whether the array// contains a set of// contiguous integers#include <bits/stdc++.h>using namespace std; // function to check// whether the array// contains a set of// contiguous integersbool areElementsContiguous(int arr[], int n){ // Find maximum and // minimum elements. int max = *max_element(arr, arr + n); int min = *min_element(arr, arr + n); int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. bool visited[m]; memset(visited, false, sizeof(visited)); // Mark elements as true. for (int i=0; i<n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i=0; i<m; i++) if (visited[i] == false) return false; return true;} // Driver programint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 34783, "s": 33606, "text": null }, { "code": "// Java implementation to// check whether the array// contains a set of// contiguous integersimport java.util.*; class GFG { // function to check // whether the array // contains a set of // contiguous integers static boolean areElementsContiguous(int arr[], int n) { // Find maximum and // minimum elements. int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { max = Math.max(max, arr[i]); min = Math.min(min, arr[i]); } int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. boolean visited[] = new boolean[n]; // Mark elements as true. for (int i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i = 0; i < m; i++) if (visited[i] == false) return false; return true; } /* Driver program */ public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}", "e": 36401, "s": 34783, "text": null }, { "code": "# Python3 implementation to# check whether the array# contains a set of# contiguous integers # function to check# whether the array# contains a set of# contiguous integersdef areElementsContiguous(arr, n): # Find maximum and # minimum elements. max1 = max(arr) min1 = min(arr) m = max1 - min1 + 1 # There should be at least # m elements in array to # make them contiguous. if (m > n): return False # Create a visited array # and initialize false visited = [0] * m # Mark elements as true. for i in range(0,n) : visited[arr[i] - min1] = True # If any element is not # marked, all elements # are not contiguous. for i in range(0, m): if (visited[i] == False): return False return True # Driver programarr = [5, 2, 3, 6, 4, 4, 6, 6 ]n = len(arr) if (areElementsContiguous(arr, n)): print(\"Yes\")else: print(\"No\") # This code is contributed by Smitha Dinesh Semwal", "e": 37380, "s": 36401, "text": null }, { "code": "// C# implementation to check whether// the array contains a set of// contiguous integersusing System; class GFG { // function to check whether the // array contains a set of // contiguous integers static bool areElementsContiguous( int []arr, int n) { // Find maximum and // minimum elements. int max = int.MinValue; int min = int.MaxValue; for(int i = 0; i < n; i++) { max = Math.Max(max, arr[i]); min = Math.Min(min, arr[i]); } int m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. bool []visited = new bool[n]; // Mark elements as true. for (int i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (int i = 0; i < m; i++) if (visited[i] == false) return false; return true; } /* Driver program */ public static void Main() { int []arr = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.Length; if (areElementsContiguous(arr, n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by nitin mittal.", "e": 38948, "s": 37380, "text": null }, { "code": "<script> // Javascript implementation to // check whether the array // contains a set of // contiguous integers // function to check whether the // array contains a set of // contiguous integers function areElementsContiguous(arr, n) { // Find maximum and // minimum elements. let max = Number.MIN_VALUE; let min = Number.MAX_VALUE; for(let i = 0; i < n; i++) { max = Math.max(max, arr[i]); min = Math.min(min, arr[i]); } let m = max - min + 1; // There should be at least // m elements in array to // make them contiguous. if (m > n) return false; // Create a visited array // and initialize false. let visited = new Array(n); visited.fill(false); // Mark elements as true. for (let i = 0; i < n; i++) visited[arr[i] - min] = true; // If any element is not // marked, all elements // are not contiguous. for (let i = 0; i < m; i++) if (visited[i] == false) return false; return true; } let arr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]; let n = arr.length; if (areElementsContiguous(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 40382, "s": 38948, "text": null }, { "code": null, "e": 40391, "s": 40382, "text": "Output: " }, { "code": null, "e": 40395, "s": 40391, "text": "Yes" }, { "code": null, "e": 40417, "s": 40395, "text": "Time Complexity: O(n)" }, { "code": null, "e": 40891, "s": 40417, "text": "Efficient solution using the hash table Insert all the elements in the hash table. Now pick the first element and keep on incrementing in its value by 1 till you find a value not present in the hash table. Again pick the first element and keep on decrementing in its value by 1 till you find a value not present in the hash table. Get the count of elements (obtained by this process) that are present in the hash table. If the count equals hash size print “Yes” else “No”. " }, { "code": null, "e": 40895, "s": 40891, "text": "C++" }, { "code": null, "e": 40900, "s": 40895, "text": "Java" }, { "code": null, "e": 40907, "s": 40900, "text": "Python" }, { "code": null, "e": 40910, "s": 40907, "text": "C#" }, { "code": null, "e": 40921, "s": 40910, "text": "Javascript" }, { "code": "// C++ implementation to check whether the array// contains a set of contiguous integers#include <bits/stdc++.h>using namespace std; // Function to check whether the array contains// a set of contiguous integersbool areElementsContiguous(int arr[], int n){ // Storing elements of 'arr[]' in a hash // table 'us' unordered_set<int> us; for (int i = 0; i < n; i++) us.insert(arr[i]); // as arr[0] is present in 'us' int count = 1; // starting with previous smaller element // of arr[0] int curr_ele = arr[0] - 1; // if 'curr_ele' is present in 'us' while (us.find(curr_ele) != us.end()) { // increment count count++; // update 'curr_ele\" curr_ele--; } // starting with next greater element // of arr[0] curr_ele = arr[0] + 1; // if 'curr_ele' is present in 'us' while (us.find(curr_ele) != us.end()) { // increment count count++; // update 'curr_ele\" curr_ele++; } // returns true if array contains a set of // contiguous integers else returns false return (count == (int)(us.size()));} // Driver program to test aboveint main(){ int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = sizeof(arr) / sizeof(arr[0]); if (areElementsContiguous(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 42275, "s": 40921, "text": null }, { "code": "// Java implementation to check whether the array// contains a set of contiguous integersimport java.io.*;import java.util.*; class GFG { // Function to check whether the array // contains a set of contiguous integers static Boolean areElementsContiguous(int arr[], int n) { // Storing elements of 'arr[]' in // a hash table 'us' HashSet<Integer> us = new HashSet<Integer>(); for (int i = 0; i < n; i++) us.add(arr[i]); // As arr[0] is present in 'us' int count = 1; // Starting with previous smaller // element of arr[0] int curr_ele = arr[0] - 1; // If 'curr_ele' is present in 'us' while (us.contains(curr_ele) == true) { // increment count count++; // update 'curr_ele\" curr_ele--; } // Starting with next greater // element of arr[0] curr_ele = arr[0] + 1; // If 'curr_ele' is present in 'us' while (us.contains(curr_ele) == true) { // increment count count++; // update 'curr_ele\" curr_ele++; } // Returns true if array contains a set of // contiguous integers else returns false return (count == (us.size())); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 }; int n = arr.length; if (areElementsContiguous(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by 'Gitanjali'.", "e": 43902, "s": 42275, "text": null }, { "code": "# Python implementation to check whether the array# contains a set of contiguous integers # Function to check whether the array# contains a set of contiguous integersdef areElementsContiguous(arr): # Storing elements of 'arr[]' in a hash table 'us' us = set() for i in arr: us.add(i) # As arr[0] is present in 'us' count = 1 # Starting with previous smaller element of arr[0] curr_ele = arr[0] - 1 # If 'curr_ele' is present in 'us' while curr_ele in us: # Increment count count += 1 # Update 'curr_ele\" curr_ele -= 1 # Starting with next greater element of arr[0] curr_ele = arr[0] + 1 # If 'curr_ele' is present in 'us' while curr_ele in us: # Increment count count += 1 # Update 'curr_ele\" curr_ele += 1 # Returns true if array contains a set of # contiguous integers else returns false return (count == len(us)) # Driver codearr = [ 5, 2, 3, 6, 4, 4, 6, 6 ]if areElementsContiguous(arr): print(\"Yes\")else: print(\"No\") # This code is contributed by 'Ansu Kumari'", "e": 44982, "s": 43902, "text": null }, { "code": "using System;using System.Collections.Generic; // c# implementation to check whether the array// contains a set of contiguous integers public class GFG{ // Function to check whether the array // contains a set of contiguous integers public static bool? areElementsContiguous(int[] arr, int n) { // Storing elements of 'arr[]' in // a hash table 'us' HashSet<int> us = new HashSet<int>(); for (int i = 0; i < n; i++) { us.Add(arr[i]); } // As arr[0] is present in 'us' int count = 1; // Starting with previous smaller // element of arr[0] int curr_ele = arr[0] - 1; // If 'curr_ele' is present in 'us' while (us.Contains(curr_ele) == true) { // increment count count++; // update 'curr_ele\" curr_ele--; } // Starting with next greater // element of arr[0] curr_ele = arr[0] + 1; // If 'curr_ele' is present in 'us' while (us.Contains(curr_ele) == true) { // increment count count++; // update 'curr_ele\" curr_ele++; } // Returns true if array contains a set of // contiguous integers else returns false return (count == (us.Count)); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {5, 2, 3, 6, 4, 4, 6, 6}; int n = arr.Length; if (areElementsContiguous(arr, n).Value) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); } }} // This code is contributed by Shrikant13", "e": 46686, "s": 44982, "text": null }, { "code": "<script> // Javascript implementation to check whether the array// contains a set of contiguous integers // Function to check whether the array contains// a set of contiguous integersfunction areElementsContiguous(arr, n){ // Storing elements of 'arr[]' in a hash // table 'us' var us = new Set(); for (var i = 0; i < n; i++) us.add(arr[i]); // as arr[0] is present in 'us' var count = 1; // starting with previous smaller element // of arr[0] var curr_ele = arr[0] - 1; // if 'curr_ele' is present in 'us' while (us.has(curr_ele)) { // increment count count++; // update 'curr_ele\" curr_ele--; } // starting with next greater element // of arr[0] curr_ele = arr[0] + 1; // if 'curr_ele' is present in 'us' while (us.has(curr_ele)) { // increment count count++; // update 'curr_ele\" curr_ele++; } // returns true if array contains a set of // contiguous integers else returns false return (count == (us.size));} // Driver program to test abovevar arr = [5, 2, 3, 6, 4, 4, 6, 6];var n = arr.length;if (areElementsContiguous(arr, n)) document.write( \"Yes\");else document.write( \"No\"); // This code is contributed by rutvik_56.</script>", "e": 47964, "s": 46686, "text": null }, { "code": null, "e": 47975, "s": 47964, "text": "Output : " }, { "code": null, "e": 47979, "s": 47975, "text": "Yes" }, { "code": null, "e": 48025, "s": 47979, "text": "Time Complexity: O(n). Auxiliary Space: O(n)." }, { "code": null, "e": 48186, "s": 48025, "text": "This method requires only one traversal of the given array. It traverses the hash table after array traversal (the hash table contains only distinct elements). " }, { "code": null, "e": 48199, "s": 48186, "text": "nitin mittal" }, { "code": null, "e": 48211, "s": 48199, "text": "shrikanth13" }, { "code": null, "e": 48217, "s": 48211, "text": "jit_t" }, { "code": null, "e": 48232, "s": 48217, "text": "rameshtravel07" }, { "code": null, "e": 48250, "s": 48232, "text": "divyeshrabadiya07" }, { "code": null, "e": 48260, "s": 48250, "text": "rutvik_56" }, { "code": null, "e": 48269, "s": 48260, "text": "sweetyty" }, { "code": null, "e": 48286, "s": 48269, "text": "surinderdawra388" }, { "code": null, "e": 48301, "s": 48286, "text": "adityakumar129" }, { "code": null, "e": 48314, "s": 48301, "text": "simmytarika5" }, { "code": null, "e": 48321, "s": 48314, "text": "Amazon" }, { "code": null, "e": 48334, "s": 48321, "text": "java-hashset" }, { "code": null, "e": 48341, "s": 48334, "text": "Arrays" }, { "code": null, "e": 48346, "s": 48341, "text": "Hash" }, { "code": null, "e": 48354, "s": 48346, "text": "Sorting" }, { "code": null, "e": 48361, "s": 48354, "text": "Amazon" }, { "code": null, "e": 48368, "s": 48361, "text": "Arrays" }, { "code": null, "e": 48373, "s": 48368, "text": "Hash" }, { "code": null, "e": 48381, "s": 48373, "text": "Sorting" }, { "code": null, "e": 48479, "s": 48381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48547, "s": 48479, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 48595, "s": 48547, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 48639, "s": 48595, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 48671, "s": 48639, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 48694, "s": 48671, "text": "Introduction to Arrays" }, { "code": null, "e": 48779, "s": 48694, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 48815, "s": 48779, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 48846, "s": 48815, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 48880, "s": 48846, "text": "Hashing | Set 3 (Open Addressing)" } ]
Fitting Shelves Problem
11 Jun, 2022 Given length of wall w and shelves of two lengths m and n, find the number of each type of shelf to be used and the remaining empty space in the optimal solution so that the empty space is minimum. The larger of the two shelves is cheaper so it is preferred. However cost is secondary and first priority is to minimize empty space on wall. Examples: Input : w = 24 m = 3 n = 5 Output : 3 3 0 We use three units of both shelves and 0 space is left. 3 * 3 + 3 * 5 = 24 So empty space = 24 - 24 = 0 Another solution could have been 8 0 0 but since the larger shelf of length 5 is cheaper the former will be the answer. Input : w = 29 m = 3 n = 9 Output : 0 3 2 0 * 3 + 3 * 9 = 27 29 - 27 = 2 Input : w = 24 m = 4 n = 7 Output : 6 0 0 6 * 4 + 0 * 7 = 24 24 - 24 = 0 A simple and efficient approach will be to try all possible combinations of shelves that fit within the length of the wall. To implement this approach along with the constraint that larger shelf costs less than the smaller one, starting from 0, we increase no of larger type shelves till they can be fit. For each case we calculate the empty space and finally store that value which minimizes the empty space. if empty space is same in two cases we prefer the one with more no of larger shelves. Below is its implementation. C++ C Java Python3 C# PHP Javascript // C++ program to find minimum space and units// of two shelves to fill a wall.#include <bits/stdc++.h>using namespace std; void minSpacePreferLarge(int wall, int m, int n){ // for simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } cout << num_m << " " << num_n << " " << min_empty << endl;} // Driver codeint main(){ int wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); return 0;} // C program to find minimum space and units// of two shelves to fill a wall.#include <stdio.h> void minSpacePreferLarge(int wall, int m, int n){ // for simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall / m, q = 0, rem = wall % m; num_m = p; num_n = q; min_empty = rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } printf("%d %d %d\n", num_m, num_n, min_empty);} // Driver codeint main(){ int wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); return 0;} // This code is contributed by rexomkar. // Java program to count all rotation// divisible by 4. public class GFG { static void minSpacePreferLarge(int wall, int m, int n) { // For simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } // place one more shelf of length n q += 1; wall = wall - n; } System.out.println(num_m + " " + num_n + " " + min_empty); } // Driver Code public static void main(String[] args) { int wall = 24, m = 3, n = 5; minSpacePreferLarge(wall, m, n); wall = 24; m = 4; n = 7; minSpacePreferLarge(wall, m, n); }} // This code is contributed by Saket Kumar def minSpacePreferLarge(w, m, n): # initialize result variables num_m = 0 num_n = 0 rem = w # p and q are no of shelves of length m & # n respectively. r is the remainder uncovered # wall length p = w//m q = 0 rem=w%m; num_m=p; num_n=q; min_empty=rem; while (w >= n): q += 1; w-= n; p = w // m r = w % m if (r <= rem): num_m = p num_n = q rem = r q += 1 w -= n print( str(int(num_m)) + " " + str(num_n) + " " + str(rem)) # Driver codew = 24m = 3n = 5minSpacePreferLarge(w, m, n) w = 24m = 4n = 7minSpacePreferLarge(w, m, n) // C# program to count all rotation// divisible by 4.using System; class GFG { static void minSpacePreferLarge(int wall, int m, int n) { // For simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } // place one more shelf of length n q += 1; wall = wall - n; } Console.WriteLine(num_m + " " + num_n + " " + min_empty); } // Driver code static public void Main() { int wall = 24, m = 3, n = 5; minSpacePreferLarge(wall, m, n); wall = 24; m = 4; n = 7; minSpacePreferLarge(wall, m, n); }} // This code is contributed by Tushil. <?php// PHP program to find minimum space and units// of two shelves to fill a wall. function minSpacePreferLarge($wall, $m, $n){ // for simplicity, Assuming m is always smaller than n // initializing output variables $num_m = 0; $num_n = 0; $min_empty = $wall; // p and q are no of shelves of length m and n // rem is the empty space $p = $wall/$m $q = 0 $rem=$wall%$m; $num_m=$p; $num_n=$q; $min_empty=$rem; while ($wall >= $n) { $q += 1; $wall = $wall - $n; // place as many shelves of length m // in the remaining part $p = $wall / $m; $rem = $wall % $m; // update output variablse if curr // min_empty <= overall empty if ($rem <= $min_empty) { $num_m = $p; $num_n = $q; $min_empty = $rem; } // place one more shelf of length n $q += 1; $wall = $wall - $n; } echo $num_m , " ", $num_n , " ", $min_empty ,"\n";} // Driver code $wall = 24; $m = 3; $n = 5; minSpacePreferLarge($wall, $m, $n); $wall = 24; $m = 4; $n = 7; minSpacePreferLarge($wall, $m, $n); // This code is contributed by ajit.?> <script> // Javascript program to count all rotation divisible by 4. function minSpacePreferLarge(wall, m, n) { // for simplicity, Assuming m is always smaller than n // initializing output variables let num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space let p = parseInt(wall/m, 10), q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = parseInt(wall / m, 10); rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } document.write(num_m + " " + num_n + " " + min_empty + "</br>"); } let wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); </script> 0 3 2 6 7 0 Time Complexity: O(w/max(n,m)) Space Complexity: O(1) References: Sumologic Internship questionThis article is contributed by Aditi Sharma. 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. BonnyHaveliwala jit_t moinaleeahmad suresh07 amartyaghoshgfg varunh92 rexomkar Sumologic Greedy Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jun, 2022" }, { "code": null, "e": 394, "s": 54, "text": "Given length of wall w and shelves of two lengths m and n, find the number of each type of shelf to be used and the remaining empty space in the optimal solution so that the empty space is minimum. The larger of the two shelves is cheaper so it is preferred. However cost is secondary and first priority is to minimize empty space on wall." }, { "code": null, "e": 405, "s": 394, "text": "Examples: " }, { "code": null, "e": 822, "s": 405, "text": "Input : w = 24 m = 3 n = 5\nOutput : 3 3 0\nWe use three units of both shelves\nand 0 space is left.\n3 * 3 + 3 * 5 = 24\nSo empty space = 24 - 24 = 0\nAnother solution could have been 8 0 0\nbut since the larger shelf of length 5\nis cheaper the former will be the answer.\n\nInput : w = 29 m = 3 n = 9 \nOutput : 0 3 2\n0 * 3 + 3 * 9 = 27\n29 - 27 = 2\n\nInput : w = 24 m = 4 n = 7 \nOutput : 6 0 0\n6 * 4 + 0 * 7 = 24\n24 - 24 = 0" }, { "code": null, "e": 1319, "s": 822, "text": "A simple and efficient approach will be to try all possible combinations of shelves that fit within the length of the wall. To implement this approach along with the constraint that larger shelf costs less than the smaller one, starting from 0, we increase no of larger type shelves till they can be fit. For each case we calculate the empty space and finally store that value which minimizes the empty space. if empty space is same in two cases we prefer the one with more no of larger shelves. " }, { "code": null, "e": 1349, "s": 1319, "text": "Below is its implementation. " }, { "code": null, "e": 1353, "s": 1349, "text": "C++" }, { "code": null, "e": 1355, "s": 1353, "text": "C" }, { "code": null, "e": 1360, "s": 1355, "text": "Java" }, { "code": null, "e": 1368, "s": 1360, "text": "Python3" }, { "code": null, "e": 1371, "s": 1368, "text": "C#" }, { "code": null, "e": 1375, "s": 1371, "text": "PHP" }, { "code": null, "e": 1386, "s": 1375, "text": "Javascript" }, { "code": "// C++ program to find minimum space and units// of two shelves to fill a wall.#include <bits/stdc++.h>using namespace std; void minSpacePreferLarge(int wall, int m, int n){ // for simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } cout << num_m << \" \" << num_n << \" \" << min_empty << endl;} // Driver codeint main(){ int wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); return 0;}", "e": 2537, "s": 1386, "text": null }, { "code": "// C program to find minimum space and units// of two shelves to fill a wall.#include <stdio.h> void minSpacePreferLarge(int wall, int m, int n){ // for simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall / m, q = 0, rem = wall % m; num_m = p; num_n = q; min_empty = rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } printf(\"%d %d %d\\n\", num_m, num_n, min_empty);} // Driver codeint main(){ int wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); return 0;} // This code is contributed by rexomkar.", "e": 3685, "s": 2537, "text": null }, { "code": "// Java program to count all rotation// divisible by 4. public class GFG { static void minSpacePreferLarge(int wall, int m, int n) { // For simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } // place one more shelf of length n q += 1; wall = wall - n; } System.out.println(num_m + \" \" + num_n + \" \" + min_empty); } // Driver Code public static void main(String[] args) { int wall = 24, m = 3, n = 5; minSpacePreferLarge(wall, m, n); wall = 24; m = 4; n = 7; minSpacePreferLarge(wall, m, n); }} // This code is contributed by Saket Kumar", "e": 5050, "s": 3685, "text": null }, { "code": "def minSpacePreferLarge(w, m, n): # initialize result variables num_m = 0 num_n = 0 rem = w # p and q are no of shelves of length m & # n respectively. r is the remainder uncovered # wall length p = w//m q = 0 rem=w%m; num_m=p; num_n=q; min_empty=rem; while (w >= n): q += 1; w-= n; p = w // m r = w % m if (r <= rem): num_m = p num_n = q rem = r q += 1 w -= n print( str(int(num_m)) + \" \" + str(num_n) + \" \" + str(rem)) # Driver codew = 24m = 3n = 5minSpacePreferLarge(w, m, n) w = 24m = 4n = 7minSpacePreferLarge(w, m, n)", "e": 5703, "s": 5050, "text": null }, { "code": "// C# program to count all rotation// divisible by 4.using System; class GFG { static void minSpacePreferLarge(int wall, int m, int n) { // For simplicity, Assuming m is always smaller than n // initializing output variables int num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space int p = wall/m, q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = wall / m; rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } // place one more shelf of length n q += 1; wall = wall - n; } Console.WriteLine(num_m + \" \" + num_n + \" \" + min_empty); } // Driver code static public void Main() { int wall = 24, m = 3, n = 5; minSpacePreferLarge(wall, m, n); wall = 24; m = 4; n = 7; minSpacePreferLarge(wall, m, n); }} // This code is contributed by Tushil.", "e": 7079, "s": 5703, "text": null }, { "code": "<?php// PHP program to find minimum space and units// of two shelves to fill a wall. function minSpacePreferLarge($wall, $m, $n){ // for simplicity, Assuming m is always smaller than n // initializing output variables $num_m = 0; $num_n = 0; $min_empty = $wall; // p and q are no of shelves of length m and n // rem is the empty space $p = $wall/$m $q = 0 $rem=$wall%$m; $num_m=$p; $num_n=$q; $min_empty=$rem; while ($wall >= $n) { $q += 1; $wall = $wall - $n; // place as many shelves of length m // in the remaining part $p = $wall / $m; $rem = $wall % $m; // update output variablse if curr // min_empty <= overall empty if ($rem <= $min_empty) { $num_m = $p; $num_n = $q; $min_empty = $rem; } // place one more shelf of length n $q += 1; $wall = $wall - $n; } echo $num_m , \" \", $num_n , \" \", $min_empty ,\"\\n\";} // Driver code $wall = 24; $m = 3; $n = 5; minSpacePreferLarge($wall, $m, $n); $wall = 24; $m = 4; $n = 7; minSpacePreferLarge($wall, $m, $n); // This code is contributed by ajit.?>", "e": 8307, "s": 7079, "text": null }, { "code": "<script> // Javascript program to count all rotation divisible by 4. function minSpacePreferLarge(wall, m, n) { // for simplicity, Assuming m is always smaller than n // initializing output variables let num_m = 0, num_n = 0, min_empty = wall; // p and q are no of shelves of length m and n // rem is the empty space let p = parseInt(wall/m, 10), q = 0, rem=wall%m; num_m=p; num_n=q; min_empty=rem; while (wall >= n) { // place one more shelf of length n q += 1; wall = wall - n; // place as many shelves of length m // in the remaining part p = parseInt(wall / m, 10); rem = wall % m; // update output variablse if curr // min_empty <= overall empty if (rem <= min_empty) { num_m = p; num_n = q; min_empty = rem; } } document.write(num_m + \" \" + num_n + \" \" + min_empty + \"</br>\"); } let wall = 29, m = 3, n = 9; minSpacePreferLarge(wall, m, n); wall = 76, m = 1, n = 10; minSpacePreferLarge(wall, m, n); </script>", "e": 9514, "s": 8307, "text": null }, { "code": null, "e": 9526, "s": 9514, "text": "0 3 2\n6 7 0" }, { "code": null, "e": 9557, "s": 9526, "text": "Time Complexity: O(w/max(n,m))" }, { "code": null, "e": 9580, "s": 9557, "text": "Space Complexity: O(1)" }, { "code": null, "e": 10042, "s": 9580, "text": "References: Sumologic Internship questionThis article is contributed by Aditi Sharma. 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": 10058, "s": 10042, "text": "BonnyHaveliwala" }, { "code": null, "e": 10064, "s": 10058, "text": "jit_t" }, { "code": null, "e": 10078, "s": 10064, "text": "moinaleeahmad" }, { "code": null, "e": 10087, "s": 10078, "text": "suresh07" }, { "code": null, "e": 10103, "s": 10087, "text": "amartyaghoshgfg" }, { "code": null, "e": 10112, "s": 10103, "text": "varunh92" }, { "code": null, "e": 10121, "s": 10112, "text": "rexomkar" }, { "code": null, "e": 10131, "s": 10121, "text": "Sumologic" }, { "code": null, "e": 10138, "s": 10131, "text": "Greedy" }, { "code": null, "e": 10145, "s": 10138, "text": "Greedy" } ]
How can we set PRIMARY KEY on multiple columns of an existing MySQL table?
We can set PRIMARY KEY constraint on multiple columns of an existing table by using ADD keyword along with ALTER TABLE statement. Suppose we have a table ‘Room_allotment’ as follows − mysql> Create table Room_allotment(Id Int, Name Varchar(20), RoomNo Int); Query OK, 0 rows affected (0.20 sec) mysql> Describe Room_allotment; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | Id | int(11) | YES | | NULL | | | Name | varchar(20) | YES | | NULL | | | RoomNo | int(11) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.11 sec) Now we can add composite PRIMARY KEY on multiple columns, ‘id’ and ‘Name’, with the following query mysql> Alter Table Room_allotment ADD PRIMARY KEY(Id, Name); Query OK, 0 rows affected (0.29 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> Describe Room_allotment; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | Id | int(11) | NO | PRI | 0 | | | Name | varchar(20) | NO | PRI | | | | RoomNo | int(11) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.12 sec) It can be observed from the above result set that PRIMARY KEY has been added on multiple columns.
[ { "code": null, "e": 1317, "s": 1187, "text": "We can set PRIMARY KEY constraint on multiple columns of an existing table by using ADD keyword along with ALTER TABLE statement." }, { "code": null, "e": 1371, "s": 1317, "text": "Suppose we have a table ‘Room_allotment’ as follows −" }, { "code": null, "e": 1932, "s": 1371, "text": "mysql> Create table Room_allotment(Id Int, Name Varchar(20), RoomNo Int);\nQuery OK, 0 rows affected (0.20 sec)\n\nmysql> Describe Room_allotment;\n+--------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-------------+------+-----+---------+-------+\n| Id | int(11) | YES | | NULL | |\n| Name | varchar(20) | YES | | NULL | |\n| RoomNo | int(11) | YES | | NULL | |\n+--------+-------------+------+-----+---------+-------+\n3 rows in set (0.11 sec)" }, { "code": null, "e": 2032, "s": 1932, "text": "Now we can add composite PRIMARY KEY on multiple columns, ‘id’ and ‘Name’, with the following query" }, { "code": null, "e": 2619, "s": 2032, "text": "mysql> Alter Table Room_allotment ADD PRIMARY KEY(Id, Name);\nQuery OK, 0 rows affected (0.29 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\n\nmysql> Describe Room_allotment;\n+--------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------+-------------+------+-----+---------+-------+\n| Id | int(11) | NO | PRI | 0 | |\n| Name | varchar(20) | NO | PRI | | |\n| RoomNo | int(11) | YES | | NULL | |\n+--------+-------------+------+-----+---------+-------+\n3 rows in set (0.12 sec)" }, { "code": null, "e": 2717, "s": 2619, "text": "It can be observed from the above result set that PRIMARY KEY has been added on multiple columns." } ]
Joining Excel Data from Multiple files using Python Pandas
17 Aug, 2020 Let us see how to join the data of two excel files and save the merged data as a new Excel file. We have 2 files, registration details.xlsx and exam results.xlsx. registration details.xlsx We are having 7 columns in this file with 14 unique students details. Column names are as follows : Admission Date Name of Student Gender DOB Student email Id Enquiry No. Registration No. exam results.xlsx We are having 7 columns in this file with 32 unique students’ details. Column names are as follows : Registration No. Name No.of questions attempted Correct Incorrect Marks Obtained Percentage You can download these files from these links : registration details.xlsx and exam results.xlsx. Now, let’s see the common columns between these two files : So the common column between the excel files is REGISTRATION NO. So we need to merge these two files in such a way that the new excel file will only hold the required columns i.e. : Algorithm : Import the Pandas module.Read both the files using the read_excel() function.Combine them using the merge() function.Use the to_excel() function, to create the resultant file. Import the Pandas module. Read both the files using the read_excel() function. Combine them using the merge() function. Use the to_excel() function, to create the resultant file. # importing the moduleimport pandas # reading the filesf1 = pandas.read_excel("registration details.xlsx")f2 = pandas.read_excel("exam results.xlsx") # merging the filesf3 = f1[["REGISTRATION NO", "STUDENT EMAIL ID "]].merge(f2[["REGISTRATION NO", "Name", "Marks Obtained", "Percentage"]], on = "REGISTRATION NO", how = "left") # creating a new filef3.to_excel("Results.xlsx", index = False) Output : Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Aug, 2020" }, { "code": null, "e": 150, "s": 52, "text": "Let us see how to join the data of two excel files and save the merged data as a new Excel file." }, { "code": null, "e": 216, "s": 150, "text": "We have 2 files, registration details.xlsx and exam results.xlsx." }, { "code": null, "e": 242, "s": 216, "text": "registration details.xlsx" }, { "code": null, "e": 342, "s": 242, "text": "We are having 7 columns in this file with 14 unique students details. Column names are as follows :" }, { "code": null, "e": 357, "s": 342, "text": "Admission Date" }, { "code": null, "e": 373, "s": 357, "text": "Name of Student" }, { "code": null, "e": 380, "s": 373, "text": "Gender" }, { "code": null, "e": 384, "s": 380, "text": "DOB" }, { "code": null, "e": 401, "s": 384, "text": "Student email Id" }, { "code": null, "e": 413, "s": 401, "text": "Enquiry No." }, { "code": null, "e": 430, "s": 413, "text": "Registration No." }, { "code": null, "e": 448, "s": 430, "text": "exam results.xlsx" }, { "code": null, "e": 549, "s": 448, "text": "We are having 7 columns in this file with 32 unique students’ details. Column names are as follows :" }, { "code": null, "e": 566, "s": 549, "text": "Registration No." }, { "code": null, "e": 571, "s": 566, "text": "Name" }, { "code": null, "e": 597, "s": 571, "text": "No.of questions attempted" }, { "code": null, "e": 605, "s": 597, "text": "Correct" }, { "code": null, "e": 615, "s": 605, "text": "Incorrect" }, { "code": null, "e": 630, "s": 615, "text": "Marks Obtained" }, { "code": null, "e": 641, "s": 630, "text": "Percentage" }, { "code": null, "e": 738, "s": 641, "text": "You can download these files from these links : registration details.xlsx and exam results.xlsx." }, { "code": null, "e": 798, "s": 738, "text": "Now, let’s see the common columns between these two files :" }, { "code": null, "e": 980, "s": 798, "text": "So the common column between the excel files is REGISTRATION NO. So we need to merge these two files in such a way that the new excel file will only hold the required columns i.e. :" }, { "code": null, "e": 992, "s": 980, "text": "Algorithm :" }, { "code": null, "e": 1168, "s": 992, "text": "Import the Pandas module.Read both the files using the read_excel() function.Combine them using the merge() function.Use the to_excel() function, to create the resultant file." }, { "code": null, "e": 1194, "s": 1168, "text": "Import the Pandas module." }, { "code": null, "e": 1247, "s": 1194, "text": "Read both the files using the read_excel() function." }, { "code": null, "e": 1288, "s": 1247, "text": "Combine them using the merge() function." }, { "code": null, "e": 1347, "s": 1288, "text": "Use the to_excel() function, to create the resultant file." }, { "code": "# importing the moduleimport pandas # reading the filesf1 = pandas.read_excel(\"registration details.xlsx\")f2 = pandas.read_excel(\"exam results.xlsx\") # merging the filesf3 = f1[[\"REGISTRATION NO\", \"STUDENT EMAIL ID \"]].merge(f2[[\"REGISTRATION NO\", \"Name\", \"Marks Obtained\", \"Percentage\"]], on = \"REGISTRATION NO\", how = \"left\") # creating a new filef3.to_excel(\"Results.xlsx\", index = False)", "e": 1907, "s": 1347, "text": null }, { "code": null, "e": 1916, "s": 1907, "text": "Output :" }, { "code": null, "e": 1930, "s": 1916, "text": "Python-pandas" }, { "code": null, "e": 1937, "s": 1930, "text": "Python" }, { "code": null, "e": 2035, "s": 1937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2053, "s": 2035, "text": "Python Dictionary" }, { "code": null, "e": 2095, "s": 2053, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2117, "s": 2095, "text": "Enumerate() in Python" }, { "code": null, "e": 2152, "s": 2117, "text": "Read a file line by line in Python" }, { "code": null, "e": 2178, "s": 2152, "text": "Python String | replace()" }, { "code": null, "e": 2210, "s": 2178, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2239, "s": 2210, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2269, "s": 2239, "text": "Iterate over a list in Python" }, { "code": null, "e": 2296, "s": 2269, "text": "Python Classes and Objects" } ]
Populate Inorder Successor for all nodes
06 Jun, 2022 Given a Binary Tree where each node has the following structure, write a function to populate the next pointer for all nodes. The next pointer for every node should be set to point to inorder successor. C++ C Java Python3 C# Javascript class node {public: int data; node* left; node* right; node* next;}; // This code is contributed// by Shubham Singh struct node { int data; struct node* left; struct node* right; struct node* next;} // A binary tree nodeclass Node { int data; Node left, right, next; Node(int item) { data = item; left = right = next = null; }} // This code is contributed by SUBHAMSINGH10. class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.next = None # This code is contributed by Shubham Singh class Node { public int data; public Node left, right, next; public Node(int item) { data = item; left = right = next = null; }}Node root; // This code is contributed// by Shubham Singh <script>class Node{ constructor(x) { this.data = x; this.left = null; this.right = null; }} // This code is contributed by Shubham Singh</script> Initially, all next pointers have NULL values. Your function should fill these next pointers so that they point to inorder successor. Solution (Use Reverse Inorder Traversal) Traverse the given tree in reverse inorder traversal and keep track of previously visited node. When a node is being visited, assign a previously visited node as next. C++ Java Python3 C# Javascript // C++ program to populate inorder// traversal of all nodes#include <bits/stdc++.h>using namespace std; class node {public: int data; node* left; node* right; node* next;}; /* Set next of p and all descendants of pby traversing them in reverse Inorder */void populateNext(node* p){ // The first visited node will be the // rightmost node next of the rightmost // node will be NULL static node* next = NULL; if (p) { // First set the next pointer // in right subtree populateNext(p->right); // Set the next as previously visited // node in reverse Inorder p->next = next; // Change the prev for subsequent node next = p; // Finally, set the next pointer in // left subtree populateNext(p->left); }} /* UTILITY FUNCTIONS *//* Helper function that allocates a newnode with the given data and NULL leftand right pointers. */node* newnode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; Node->next = NULL; return (Node);} // Driver Codeint main(){ /* Constructed binary tree is 10 / \ 8 12 / 3 */ node* root = newnode(10); root->left = newnode(8); root->right = newnode(12); root->left->left = newnode(3); // Populates nextRight pointer in all nodes populateNext(root); // Let us see the populated values node* ptr = root->left->left; while (ptr) { // -1 is printed if there is no successor cout << "Next of " << ptr->data << " is " << (ptr->next ? ptr->next->data : -1) << endl; ptr = ptr->next; } return 0;} // This code is contributed by rathbhupendra // Java program to populate inorder traversal of all nodes // A binary tree nodeclass Node { int data; Node left, right, next; Node(int item) { data = item; left = right = next = null; }} class BinaryTree { Node root; static Node next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ void populateNext(Node node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in // reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ public static void main(String args[]) { /* Constructed binary tree is 10 / \ 8 12 / 3 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.populateNext(tree.root); // Let us see the populated values Node ptr = tree.root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; System.out.println("Next of " + ptr.data + " is: " + print); ptr = ptr.next; } }} // This code has been contributed by Mayank Jaiswal # Python3 program to populate# inorder traversal of all nodes # Tree node class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.next = None # The first visited node will be# the rightmost node next of the# rightmost node will be Nonenext = None # Set next of p and all descendants of p# by traversing them in reverse Inorder def populateNext(p): global next if (p != None): # First set the next pointer # in right subtree populateNext(p.right) # Set the next as previously visited node # in reverse Inorder p.next = next # Change the prev for subsequent node next = p # Finally, set the next pointer # in left subtree populateNext(p.left) # UTILITY FUNCTIONS# Helper function that allocates# a new node with the given data# and None left and right pointers. def newnode(data): node = Node(0) node.data = data node.left = None node.right = None node.next = None return(node) # Driver Code # Constructed binary tree is# 10# / \# 8 12# /# 3root = newnode(10)root.left = newnode(8)root.right = newnode(12)root.left.left = newnode(3) # Populates nextRight pointer# in all nodesp = populateNext(root) # Let us see the populated valuesptr = root.left.leftwhile(ptr != None): out = 0 if(ptr.next != None): out = ptr.next.data else: out = -1 # -1 is printed if there is no successor print("Next of", ptr.data, "is", out) ptr = ptr.next # This code is contributed by Arnab Kundu // C# program to populate inorder traversal of all nodesusing System; class BinaryTree { // A binary tree node class Node { public int data; public Node left, right, next; public Node(int item) { data = item; left = right = next = null; } } Node root; static Node next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ void populateNext(Node node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in // reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ static public void Main(String[] args) { /* Constructed binary tree is 10 / \ 8 12 / 3 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.populateNext(tree.root); // Let us see the populated values Node ptr = tree.root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; Console.WriteLine("Next of " + ptr.data + " is: " + print); ptr = ptr.next; } }} // This code has been contributed by Arnab Kundu <script>// Javascript program to populate inorder traversal of all nodes // A binary tree node class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } let root; let next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ function populateNext(node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ /* Constructed binary tree is 10 / \ 8 12 / 3 */ root = new Node(10) root.left = new Node(8) root.right = new Node(12) root.left.left = new Node(3) // Populates nextRight pointer // in all nodes p = populateNext(root) // Let us see the populated values ptr = root.left.left while (ptr != null) { // -1 is printed if there is no successor let print = ptr.next != null ? ptr.next.data : -1; document.write("Next of " + ptr.data + " is: " + print+"<br>"); ptr = ptr.next; } // This code is contributed by unknown2108</script> Next of 3 is 8 Next of 8 is 10 Next of 10 is 12 Next of 12 is -1 We can avoid the use of static variables by passing reference to next as a parameter. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ C Java Python3 C# Javascript // An implementation that doesn't use static variable // A wrapper over populateNextRecurvoid populateNext(node* root){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL node* next = NULL; populateNextRecur(root, &next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */void populateNextRecur(node* p, node** next_ref){ if (p) { // First set the next pointer in right subtree populateNextRecur(p->right, next_ref); // Set the next as previously visited // node in reverse Inorder p->next = *next_ref; // Change the prev for subsequent node *next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p->left, next_ref); }} // This is code is contributed by rathbhupendra // An implementation that doesn't use static variable // A wrapper over populateNextRecurvoid populateNext(struct node* root){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL struct node* next = NULL; populateNextRecur(root, &next);} /* Set next of all descendants of p by traversing them in * reverse Inorder */void populateNextRecur(struct node* p, struct node** next_ref){ if (p) { // First set the next pointer in right subtree populateNextRecur(p->right, next_ref); // Set the next as previously visited node in // reverse Inorder p->next = *next_ref; // Change the prev for subsequent node *next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p->left, next_ref); }} // A wrapper over populateNextRecurvoid populateNext(Node node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p by traversing them in * reverse Inorder */void populateNextRecur(Node p, Node next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in // reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }} # A wrapper over populateNextRecurdef populateNext(node): # The first visited node will be the rightmost node # next of the rightmost node will be NULL populateNextRecur(node, next) # /* Set next of all descendants of p by# traversing them in reverse Inorder */ def populateNextRecur(p, next_ref): if (p != None): # First set the next pointer in right subtree populateNextRecur(p.right, next_ref) # Set the next as previously visited node in reverse Inorder p.next = next_ref # Change the prev for subsequent node next_ref = p # Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref) # This code is contributed by Mohit kumar 29 // A wrapper over populateNextRecurvoid populateNext(Node node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */void populateNextRecur(Node p, Node next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in // reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }} // This code is contributed by princiraj1992 <script> // A wrapper over populateNextRecurfunction populateNext(node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */function populateNextRecur(p, next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }} // This code is contributed by importantly.</script> Time Complexity: O(n) Approach: Steps: Create an array or an ArrayList.Store the inorder traversal of the binary tree into the ArrayList (nodes are to be stored).Now traverse the array and replace the next pointer of the node to the immediate right node(next element in the array which is the required inorder successor). Create an array or an ArrayList. Store the inorder traversal of the binary tree into the ArrayList (nodes are to be stored). Now traverse the array and replace the next pointer of the node to the immediate right node(next element in the array which is the required inorder successor). list.get(i).next = list.get(i+1) Implementation: Java Python3 C# Javascript import java.util.ArrayList; // class Nodeclass Node { int data; Node left, right, next; // constructor for initializing key value and all the // pointers Node(int data) { this.data = data; left = right = next = null; }} public class Solution { Node root = null; // list to store inorder sequence ArrayList<Node> list = new ArrayList<>(); // function for populating next pointer to inorder // successor void populateNext() { // list = [3,8,10,12] // inorder successor of the present node is the // immediate right node for ex: inorder successor of // 3 is 8 for (int i = 0; i < list.size(); i++) { // check if it is the last node // point next of last node(right most) to null if (i != list.size() - 1) { list.get(i).next = list.get(i + 1); } else { list.get(i).next = null; } } // Let us see the populated values Node ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; System.out.println("Next of " + ptr.data + " is: " + print); ptr = ptr.next; } } // insert the inorder into a list to keep track // of the inorder successor void inorder(Node root) { if (root != null) { inorder(root.left); list.add(root); inorder(root.right); } } // Driver function public static void main(String args[]) { Solution tree = new Solution(); /* 10 / \ 8 12 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // function calls tree.inorder(tree.root); tree.populateNext(); }} # class Nodeclass Node: def __init__(self, data): self.data = data self.next = None self.right = None self.left = None root = None # list to store inorder sequencelist = [] # function for populating next pointer to inorder successor def populateNext(root): # list = [3,8,10,12] # inorder successor of the present Node is the immediate # right Node # for ex: inorder successor of 3 is 8 for i in range(len(list)): # check if it is the last Node # point next of last Node(right most) to None if (i != len(list) - 1): list[i].next = list[i + 1] else: list[i].next = None # Let us see the populated values ptr = root.left.left while (ptr != None): # -1 is printed if there is no successor pt = -1 if(ptr.next != None): pt = ptr.next.data print("Next of ", ptr.data, " is: ", pt) ptr = ptr.next # insert the inorder into a list to keep track# of the inorder successor def inorder(root): if (root != None): inorder(root.left) list.append(root) inorder(root.right) # Driver functionif __name__ == '__main__': ''' * 10 / \ 8 12 / 3 ''' root = Node(10) root.left = Node(8) root.right = Node(12) root.left.left = Node(3) # function calls inorder(root) populateNext(root) # This code is contributed by Rajput-Ji using System;using System.Collections.Generic; // class Nodepublic class Node { public int data; public Node left, right, next; // constructor for initializing key value and all the // pointers public Node(int data) { this.data = data; left = right = next = null; }} public class Solution { Node root = null; // list to store inorder sequence List<Node> list = new List<Node>(); // function for populating next pointer to inorder // successor void populateNext() { // list = [3,8,10,12] // inorder successor of the present node is the // immediate right node for ex: inorder successor of // 3 is 8 for (int i = 0; i < list.Count; i++) { // check if it is the last node // point next of last node(right most) to null if (i != list.Count - 1) { list[i].next = list[i + 1]; } else { list[i].next = null; } } // Let us see the populated values Node ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; Console.WriteLine("Next of " + ptr.data + " is: " + print); ptr = ptr.next; } } // insert the inorder into a list to keep track // of the inorder successor void inorder(Node root) { if (root != null) { inorder(root.left); list.Add(root); inorder(root.right); } } // Driver function public static void Main(String[] args) { Solution tree = new Solution(); /* * 10 / \ 8 12 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // function calls tree.inorder(tree.root); tree.populateNext(); }} // This code is contributed by gauravrajput1 <script> // class Nodeclass Node{ // constructor for initializing key value and all the // pointers constructor(data) { this.data = data; this.left = this.right = this.next = null; }} let root = null; // list to store inorder sequencelet list = []; // function for populating next pointer to inorder successorfunction populateNext(){ // list = [3,8,10,12] // inorder successor of the present node is the immediate // right node // for ex: inorder successor of 3 is 8 for(let i = 0; i < list.length; i++) { // check if it is the last node // point next of last node(right most) to null if(i != list.length - 1) { list[i].next = list[i + 1]; } else { list[i].next = null; } } // Let us see the populated values let ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor let print = ptr.next != null ? ptr.next.data : -1; document.write("Next of " + ptr.data + " is: " + print+"<br>"); ptr = ptr.next; }} // insert the inorder into a list to keep track// of the inorder successorfunction inorder(root){ if(root != null) { inorder(root.left); list.push(root); inorder(root.right); }} // Driver function /* 10 / \ 8 12 / 3 */root = new Node(10);root.left = new Node(8);root.right = new Node(12);root.left.left = new Node(3); // function callsinorder(root);populateNext(); // This code is contributed by avanitrachhadiya2155</script> Next of 3 is: 8 Next of 8 is: 10 Next of 10 is: 12 Next of 12 is: -1 Approach – 3(Using stack) Use a stack to store all the left elements corresponding to a node to the point that the node is the leftmost node itself. After this, store all the left of the right of the leftmost node in the stack. Then, until and unless the stack is empty, point the next of the current node to the topmost element of the stack and if the topmost element of the node has a right node, store all the left element of the right of the topmost. C++ Java Python3 C# #include <iostream>#include <stack>using namespace std; struct Node { int data; struct Node* left; struct Node* right; struct Node* next; Node(int x) { data = x; left = NULL; right = NULL; next = NULL; }}; Node* inorder(Node* root){ if (root->left == NULL) return root; inorder(root->left);} void populateNext(Node* root){ stack<Node*> s; Node* temp = root; while (temp->left) { s.push(temp); temp = temp->left; } Node* curr = temp; if (curr->right) { Node* q = curr->right; while (q) { s.push(q); q = q->left; } } while (!s.empty()) { Node* inorder = s.top(); s.pop(); curr->next = inorder; if (inorder->right) { Node* q = inorder->right; while (q) { s.push(q); q = q->left; } } curr = inorder; }} Node* newnode(int data){ Node* node = new Node(data); return (node);} int main(){ /* Constructed binary tree is 10 / \ 8 12 / 3 */ Node* root = newnode(10); root->left = newnode(8); root->right = newnode(12); root->left->left = newnode(3); populateNext(root); Node* ptr = inorder(root); while (ptr) { // -1 is printed if there is no successor cout << "Next of " << ptr->data << " is " << (ptr->next ? ptr->next->data : -1) << endl; ptr = ptr->next; } return 0;} import java.util.*; class GFG{ static class Node { int data; Node left; Node right; Node next; Node(int x) { data = x; left = null; right = null; next = null; } }; static Node inorder(Node root) { if (root.left == null) return root; root = inorder(root.left); return root; } static void populateNext(Node root) { Stack<Node> s = new Stack<>(); Node temp = root; while (temp.left!=null) { s.add(temp); temp = temp.left; } Node curr = temp; if (curr.right!=null) { Node q = curr.right; while (q!=null) { s.add(q); q = q.left; } } while (!s.isEmpty()) { Node inorder = s.peek(); s.pop(); curr.next = inorder; if (inorder.right!=null) { Node q = inorder.right; while (q!=null) { s.add(q); q = q.left; } } curr = inorder; } } static Node newnode(int data) { Node node = new Node(data); return (node); } public static void main(String[] args) { /* Constructed binary tree is 10 / \ 8 12 / 3 */ Node root = newnode(10); root.left = newnode(8); root.right = newnode(12); root.left.left = newnode(3); populateNext(root); Node ptr = inorder(root); while (ptr != null) { // -1 is printed if there is no successor System.out.print("Next of " + ptr.data+ " is " + (ptr.next!=null ? ptr.next.data : -1) +"\n"); ptr = ptr.next; } }} // This code is contributed by Rajput-Ji class GFG: class Node: data = 0 left = None right = None next = None def __init__(self, x): self.data = x self.left = None self.right = None self.next = None @staticmethod def inorder(root): if (root.left == None): return root root = GFG.inorder(root.left) return root @staticmethod def populateNext(root): s = [] temp = root while (temp.left != None): s.append(temp) temp = temp.left curr = temp if (curr.right != None): q = curr.right while (q != None): s.append(q) q = q.left while (not (len(s) == 0)): inorder = s[-1] s.pop() curr.next = inorder if (inorder.right != None): q = inorder.right while (q != None): s.append(q) q = q.left curr = inorder @staticmethod def newnode(data): node = GFG.Node(data) return (node) @staticmethod def main(args): # Constructed binary tree is # 10 # / \ # 8 12 # / # 3 root = GFG.newnode(10) root.left = GFG.newnode(8) root.right = GFG.newnode(12) root.left.left = GFG.newnode(3) GFG.populateNext(root) ptr = GFG.inorder(root) while (ptr != None): # -1 is printed if there is no successor print("Next of " + str(ptr.data) + " is " + str((ptr.next.data if ptr.next != None else -1)) + "\n", end="") ptr = ptr.next if __name__ == "__main__": GFG.main([]) # This code is contributed by mukulsomukesh using System;using System.Collections.Generic; public class GFG { public class Node { public int data; public Node left; public Node right; public Node next; public Node(int x) { data = x; left = null; right = null; next = null; } }; static Node inorder(Node root) { if (root.left == null) return root; root = inorder(root.left); return root; } static void populateNext(Node root) { Stack<Node> s = new Stack<Node>(); Node temp = root; while (temp.left != null) { s.Push(temp); temp = temp.left; } Node curr = temp; if (curr.right != null) { Node q = curr.right; while (q != null) { s.Push(q); q = q.left; } } while (s.Count!=0) { Node inorder = s.Peek(); s.Pop(); curr.next = inorder; if (inorder.right != null) { Node q = inorder.right; while (q != null) { s.Push(q); q = q.left; } } curr = inorder; } } static Node newnode(int data) { Node node = new Node(data); return (node); } public static void Main(String[] args) { /* * Constructed binary tree is 10 / \ 8 12 / 3 */ Node root = newnode(10); root.left = newnode(8); root.right = newnode(12); root.left.left = newnode(3); populateNext(root); Node ptr = inorder(root); while (ptr != null) { // -1 is printed if there is no successor Console.Write("Next of " + ptr.data + " is " + (ptr.next != null ? ptr.next.data : -1) + "\n"); ptr = ptr.next; } }} // This code contributed by Rajput-Ji Next of 3 is 8 Next of 8 is 10 Next of 10 is 12 Next of 12 is -1 Complexity Analysis: Time Complexity: O(n), where n is the number of nodes in the tree. Space Complexity: O(h), where h is the height of the tree. This approach is better because it overcomes the auxiliary stack space complexity in the recursive method and the space complexity in the arrayList method because the stack will at most store the number of elements equal to height of the tree at any given time. andrew1234 rathbhupendra princiraj1992 shubham_singh Akanksha_Rai mohit kumar 29 unknown2108 avllikhita importantly avanitrachhadiya2155 kalrap615 GauravRajput1 simranarora5sos sweetyty SHUBHAMSINGH10 simmytarika5 Rajput-Ji sharmakavi59 mukulsomukesh Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jun, 2022" }, { "code": null, "e": 257, "s": 54, "text": "Given a Binary Tree where each node has the following structure, write a function to populate the next pointer for all nodes. The next pointer for every node should be set to point to inorder successor." }, { "code": null, "e": 261, "s": 257, "text": "C++" }, { "code": null, "e": 263, "s": 261, "text": "C" }, { "code": null, "e": 268, "s": 263, "text": "Java" }, { "code": null, "e": 276, "s": 268, "text": "Python3" }, { "code": null, "e": 279, "s": 276, "text": "C#" }, { "code": null, "e": 290, "s": 279, "text": "Javascript" }, { "code": "class node {public: int data; node* left; node* right; node* next;}; // This code is contributed// by Shubham Singh", "e": 418, "s": 290, "text": null }, { "code": "struct node { int data; struct node* left; struct node* right; struct node* next;}", "e": 513, "s": 418, "text": null }, { "code": "// A binary tree nodeclass Node { int data; Node left, right, next; Node(int item) { data = item; left = right = next = null; }} // This code is contributed by SUBHAMSINGH10.", "e": 718, "s": 513, "text": null }, { "code": "class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.next = None # This code is contributed by Shubham Singh", "e": 900, "s": 718, "text": null }, { "code": "class Node { public int data; public Node left, right, next; public Node(int item) { data = item; left = right = next = null; }}Node root; // This code is contributed// by Shubham Singh", "e": 1116, "s": 900, "text": null }, { "code": "<script>class Node{ constructor(x) { this.data = x; this.left = null; this.right = null; }} // This code is contributed by Shubham Singh</script>", "e": 1292, "s": 1116, "text": null }, { "code": null, "e": 1426, "s": 1292, "text": "Initially, all next pointers have NULL values. Your function should fill these next pointers so that they point to inorder successor." }, { "code": null, "e": 1635, "s": 1426, "text": "Solution (Use Reverse Inorder Traversal) Traverse the given tree in reverse inorder traversal and keep track of previously visited node. When a node is being visited, assign a previously visited node as next." }, { "code": null, "e": 1639, "s": 1635, "text": "C++" }, { "code": null, "e": 1644, "s": 1639, "text": "Java" }, { "code": null, "e": 1652, "s": 1644, "text": "Python3" }, { "code": null, "e": 1655, "s": 1652, "text": "C#" }, { "code": null, "e": 1666, "s": 1655, "text": "Javascript" }, { "code": "// C++ program to populate inorder// traversal of all nodes#include <bits/stdc++.h>using namespace std; class node {public: int data; node* left; node* right; node* next;}; /* Set next of p and all descendants of pby traversing them in reverse Inorder */void populateNext(node* p){ // The first visited node will be the // rightmost node next of the rightmost // node will be NULL static node* next = NULL; if (p) { // First set the next pointer // in right subtree populateNext(p->right); // Set the next as previously visited // node in reverse Inorder p->next = next; // Change the prev for subsequent node next = p; // Finally, set the next pointer in // left subtree populateNext(p->left); }} /* UTILITY FUNCTIONS *//* Helper function that allocates a newnode with the given data and NULL leftand right pointers. */node* newnode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; Node->next = NULL; return (Node);} // Driver Codeint main(){ /* Constructed binary tree is 10 / \\ 8 12 / 3 */ node* root = newnode(10); root->left = newnode(8); root->right = newnode(12); root->left->left = newnode(3); // Populates nextRight pointer in all nodes populateNext(root); // Let us see the populated values node* ptr = root->left->left; while (ptr) { // -1 is printed if there is no successor cout << \"Next of \" << ptr->data << \" is \" << (ptr->next ? ptr->next->data : -1) << endl; ptr = ptr->next; } return 0;} // This code is contributed by rathbhupendra", "e": 3407, "s": 1666, "text": null }, { "code": "// Java program to populate inorder traversal of all nodes // A binary tree nodeclass Node { int data; Node left, right, next; Node(int item) { data = item; left = right = next = null; }} class BinaryTree { Node root; static Node next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ void populateNext(Node node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in // reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ public static void main(String args[]) { /* Constructed binary tree is 10 / \\ 8 12 / 3 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.populateNext(tree.root); // Let us see the populated values Node ptr = tree.root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; System.out.println(\"Next of \" + ptr.data + \" is: \" + print); ptr = ptr.next; } }} // This code has been contributed by Mayank Jaiswal", "e": 5277, "s": 3407, "text": null }, { "code": "# Python3 program to populate# inorder traversal of all nodes # Tree node class Node: def __init__(self, data): self.data = data self.left = None self.right = None self.next = None # The first visited node will be# the rightmost node next of the# rightmost node will be Nonenext = None # Set next of p and all descendants of p# by traversing them in reverse Inorder def populateNext(p): global next if (p != None): # First set the next pointer # in right subtree populateNext(p.right) # Set the next as previously visited node # in reverse Inorder p.next = next # Change the prev for subsequent node next = p # Finally, set the next pointer # in left subtree populateNext(p.left) # UTILITY FUNCTIONS# Helper function that allocates# a new node with the given data# and None left and right pointers. def newnode(data): node = Node(0) node.data = data node.left = None node.right = None node.next = None return(node) # Driver Code # Constructed binary tree is# 10# / \\# 8 12# /# 3root = newnode(10)root.left = newnode(8)root.right = newnode(12)root.left.left = newnode(3) # Populates nextRight pointer# in all nodesp = populateNext(root) # Let us see the populated valuesptr = root.left.leftwhile(ptr != None): out = 0 if(ptr.next != None): out = ptr.next.data else: out = -1 # -1 is printed if there is no successor print(\"Next of\", ptr.data, \"is\", out) ptr = ptr.next # This code is contributed by Arnab Kundu", "e": 6886, "s": 5277, "text": null }, { "code": "// C# program to populate inorder traversal of all nodesusing System; class BinaryTree { // A binary tree node class Node { public int data; public Node left, right, next; public Node(int item) { data = item; left = right = next = null; } } Node root; static Node next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ void populateNext(Node node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in // reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ static public void Main(String[] args) { /* Constructed binary tree is 10 / \\ 8 12 / 3 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // Populates nextRight pointer in all nodes tree.populateNext(tree.root); // Let us see the populated values Node ptr = tree.root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; Console.WriteLine(\"Next of \" + ptr.data + \" is: \" + print); ptr = ptr.next; } }} // This code has been contributed by Arnab Kundu", "e": 8822, "s": 6886, "text": null }, { "code": "<script>// Javascript program to populate inorder traversal of all nodes // A binary tree node class Node { constructor(x) { this.data = x; this.left = null; this.right = null; } } let root; let next = null; /* Set next of p and all descendants of p by traversing them in reverse Inorder */ function populateNext(node) { // The first visited node will be the rightmost node // next of the rightmost node will be NULL if (node != null) { // First set the next pointer in right subtree populateNext(node.right); // Set the next as previously visited node in reverse Inorder node.next = next; // Change the prev for subsequent node next = node; // Finally, set the next pointer in left subtree populateNext(node.left); } } /* Driver program to test above functions*/ /* Constructed binary tree is 10 / \\ 8 12 / 3 */ root = new Node(10) root.left = new Node(8) root.right = new Node(12) root.left.left = new Node(3) // Populates nextRight pointer // in all nodes p = populateNext(root) // Let us see the populated values ptr = root.left.left while (ptr != null) { // -1 is printed if there is no successor let print = ptr.next != null ? ptr.next.data : -1; document.write(\"Next of \" + ptr.data + \" is: \" + print+\"<br>\"); ptr = ptr.next; } // This code is contributed by unknown2108</script>", "e": 10523, "s": 8822, "text": null }, { "code": null, "e": 10588, "s": 10523, "text": "Next of 3 is 8\nNext of 8 is 10\nNext of 10 is 12\nNext of 12 is -1" }, { "code": null, "e": 10675, "s": 10588, "text": "We can avoid the use of static variables by passing reference to next as a parameter. " }, { "code": null, "e": 10684, "s": 10675, "text": "Chapters" }, { "code": null, "e": 10711, "s": 10684, "text": "descriptions off, selected" }, { "code": null, "e": 10761, "s": 10711, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 10784, "s": 10761, "text": "captions off, selected" }, { "code": null, "e": 10792, "s": 10784, "text": "English" }, { "code": null, "e": 10816, "s": 10792, "text": "This is a modal window." }, { "code": null, "e": 10885, "s": 10816, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 10907, "s": 10885, "text": "End of dialog window." }, { "code": null, "e": 10911, "s": 10907, "text": "C++" }, { "code": null, "e": 10913, "s": 10911, "text": "C" }, { "code": null, "e": 10918, "s": 10913, "text": "Java" }, { "code": null, "e": 10926, "s": 10918, "text": "Python3" }, { "code": null, "e": 10929, "s": 10926, "text": "C#" }, { "code": null, "e": 10940, "s": 10929, "text": "Javascript" }, { "code": "// An implementation that doesn't use static variable // A wrapper over populateNextRecurvoid populateNext(node* root){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL node* next = NULL; populateNextRecur(root, &next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */void populateNextRecur(node* p, node** next_ref){ if (p) { // First set the next pointer in right subtree populateNextRecur(p->right, next_ref); // Set the next as previously visited // node in reverse Inorder p->next = *next_ref; // Change the prev for subsequent node *next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p->left, next_ref); }} // This is code is contributed by rathbhupendra", "e": 11792, "s": 10940, "text": null }, { "code": "// An implementation that doesn't use static variable // A wrapper over populateNextRecurvoid populateNext(struct node* root){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL struct node* next = NULL; populateNextRecur(root, &next);} /* Set next of all descendants of p by traversing them in * reverse Inorder */void populateNextRecur(struct node* p, struct node** next_ref){ if (p) { // First set the next pointer in right subtree populateNextRecur(p->right, next_ref); // Set the next as previously visited node in // reverse Inorder p->next = *next_ref; // Change the prev for subsequent node *next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p->left, next_ref); }}", "e": 12649, "s": 11792, "text": null }, { "code": "// A wrapper over populateNextRecurvoid populateNext(Node node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p by traversing them in * reverse Inorder */void populateNextRecur(Node p, Node next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in // reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }}", "e": 13379, "s": 12649, "text": null }, { "code": "# A wrapper over populateNextRecurdef populateNext(node): # The first visited node will be the rightmost node # next of the rightmost node will be NULL populateNextRecur(node, next) # /* Set next of all descendants of p by# traversing them in reverse Inorder */ def populateNextRecur(p, next_ref): if (p != None): # First set the next pointer in right subtree populateNextRecur(p.right, next_ref) # Set the next as previously visited node in reverse Inorder p.next = next_ref # Change the prev for subsequent node next_ref = p # Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref) # This code is contributed by Mohit kumar 29", "e": 14111, "s": 13379, "text": null }, { "code": "// A wrapper over populateNextRecurvoid populateNext(Node node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */void populateNextRecur(Node p, Node next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in // reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }} // This code is contributed by princiraj1992", "e": 14883, "s": 14111, "text": null }, { "code": "<script> // A wrapper over populateNextRecurfunction populateNext(node){ // The first visited node will be the rightmost node // next of the rightmost node will be NULL populateNextRecur(node, next);} /* Set next of all descendants of p bytraversing them in reverse Inorder */function populateNextRecur(p, next_ref){ if (p != null) { // First set the next pointer in right subtree populateNextRecur(p.right, next_ref); // Set the next as previously visited node in reverse Inorder p.next = next_ref; // Change the prev for subsequent node next_ref = p; // Finally, set the next pointer in right subtree populateNextRecur(p.left, next_ref); }} // This code is contributed by importantly.</script>", "e": 15692, "s": 14883, "text": null }, { "code": null, "e": 15714, "s": 15692, "text": "Time Complexity: O(n)" }, { "code": null, "e": 15724, "s": 15714, "text": "Approach:" }, { "code": null, "e": 15731, "s": 15724, "text": "Steps:" }, { "code": null, "e": 16014, "s": 15731, "text": "Create an array or an ArrayList.Store the inorder traversal of the binary tree into the ArrayList (nodes are to be stored).Now traverse the array and replace the next pointer of the node to the immediate right node(next element in the array which is the required inorder successor)." }, { "code": null, "e": 16047, "s": 16014, "text": "Create an array or an ArrayList." }, { "code": null, "e": 16139, "s": 16047, "text": "Store the inorder traversal of the binary tree into the ArrayList (nodes are to be stored)." }, { "code": null, "e": 16299, "s": 16139, "text": "Now traverse the array and replace the next pointer of the node to the immediate right node(next element in the array which is the required inorder successor)." }, { "code": null, "e": 16336, "s": 16299, "text": " list.get(i).next = list.get(i+1)" }, { "code": null, "e": 16352, "s": 16336, "text": "Implementation:" }, { "code": null, "e": 16357, "s": 16352, "text": "Java" }, { "code": null, "e": 16365, "s": 16357, "text": "Python3" }, { "code": null, "e": 16368, "s": 16365, "text": "C#" }, { "code": null, "e": 16379, "s": 16368, "text": "Javascript" }, { "code": "import java.util.ArrayList; // class Nodeclass Node { int data; Node left, right, next; // constructor for initializing key value and all the // pointers Node(int data) { this.data = data; left = right = next = null; }} public class Solution { Node root = null; // list to store inorder sequence ArrayList<Node> list = new ArrayList<>(); // function for populating next pointer to inorder // successor void populateNext() { // list = [3,8,10,12] // inorder successor of the present node is the // immediate right node for ex: inorder successor of // 3 is 8 for (int i = 0; i < list.size(); i++) { // check if it is the last node // point next of last node(right most) to null if (i != list.size() - 1) { list.get(i).next = list.get(i + 1); } else { list.get(i).next = null; } } // Let us see the populated values Node ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; System.out.println(\"Next of \" + ptr.data + \" is: \" + print); ptr = ptr.next; } } // insert the inorder into a list to keep track // of the inorder successor void inorder(Node root) { if (root != null) { inorder(root.left); list.add(root); inorder(root.right); } } // Driver function public static void main(String args[]) { Solution tree = new Solution(); /* 10 / \\ 8 12 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // function calls tree.inorder(tree.root); tree.populateNext(); }}", "e": 18443, "s": 16379, "text": null }, { "code": "# class Nodeclass Node: def __init__(self, data): self.data = data self.next = None self.right = None self.left = None root = None # list to store inorder sequencelist = [] # function for populating next pointer to inorder successor def populateNext(root): # list = [3,8,10,12] # inorder successor of the present Node is the immediate # right Node # for ex: inorder successor of 3 is 8 for i in range(len(list)): # check if it is the last Node # point next of last Node(right most) to None if (i != len(list) - 1): list[i].next = list[i + 1] else: list[i].next = None # Let us see the populated values ptr = root.left.left while (ptr != None): # -1 is printed if there is no successor pt = -1 if(ptr.next != None): pt = ptr.next.data print(\"Next of \", ptr.data, \" is: \", pt) ptr = ptr.next # insert the inorder into a list to keep track# of the inorder successor def inorder(root): if (root != None): inorder(root.left) list.append(root) inorder(root.right) # Driver functionif __name__ == '__main__': ''' * 10 / \\ 8 12 / 3 ''' root = Node(10) root.left = Node(8) root.right = Node(12) root.left.left = Node(3) # function calls inorder(root) populateNext(root) # This code is contributed by Rajput-Ji", "e": 19862, "s": 18443, "text": null }, { "code": "using System;using System.Collections.Generic; // class Nodepublic class Node { public int data; public Node left, right, next; // constructor for initializing key value and all the // pointers public Node(int data) { this.data = data; left = right = next = null; }} public class Solution { Node root = null; // list to store inorder sequence List<Node> list = new List<Node>(); // function for populating next pointer to inorder // successor void populateNext() { // list = [3,8,10,12] // inorder successor of the present node is the // immediate right node for ex: inorder successor of // 3 is 8 for (int i = 0; i < list.Count; i++) { // check if it is the last node // point next of last node(right most) to null if (i != list.Count - 1) { list[i].next = list[i + 1]; } else { list[i].next = null; } } // Let us see the populated values Node ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor int print = ptr.next != null ? ptr.next.data : -1; Console.WriteLine(\"Next of \" + ptr.data + \" is: \" + print); ptr = ptr.next; } } // insert the inorder into a list to keep track // of the inorder successor void inorder(Node root) { if (root != null) { inorder(root.left); list.Add(root); inorder(root.right); } } // Driver function public static void Main(String[] args) { Solution tree = new Solution(); /* * 10 / \\ 8 12 / 3 */ tree.root = new Node(10); tree.root.left = new Node(8); tree.root.right = new Node(12); tree.root.left.left = new Node(3); // function calls tree.inorder(tree.root); tree.populateNext(); }} // This code is contributed by gauravrajput1", "e": 21965, "s": 19862, "text": null }, { "code": "<script> // class Nodeclass Node{ // constructor for initializing key value and all the // pointers constructor(data) { this.data = data; this.left = this.right = this.next = null; }} let root = null; // list to store inorder sequencelet list = []; // function for populating next pointer to inorder successorfunction populateNext(){ // list = [3,8,10,12] // inorder successor of the present node is the immediate // right node // for ex: inorder successor of 3 is 8 for(let i = 0; i < list.length; i++) { // check if it is the last node // point next of last node(right most) to null if(i != list.length - 1) { list[i].next = list[i + 1]; } else { list[i].next = null; } } // Let us see the populated values let ptr = root.left.left; while (ptr != null) { // -1 is printed if there is no successor let print = ptr.next != null ? ptr.next.data : -1; document.write(\"Next of \" + ptr.data + \" is: \" + print+\"<br>\"); ptr = ptr.next; }} // insert the inorder into a list to keep track// of the inorder successorfunction inorder(root){ if(root != null) { inorder(root.left); list.push(root); inorder(root.right); }} // Driver function /* 10 / \\ 8 12 / 3 */root = new Node(10);root.left = new Node(8);root.right = new Node(12);root.left.left = new Node(3); // function callsinorder(root);populateNext(); // This code is contributed by avanitrachhadiya2155</script>", "e": 23739, "s": 21965, "text": null }, { "code": null, "e": 23808, "s": 23739, "text": "Next of 3 is: 8\nNext of 8 is: 10\nNext of 10 is: 12\nNext of 12 is: -1" }, { "code": null, "e": 23834, "s": 23808, "text": "Approach – 3(Using stack)" }, { "code": null, "e": 24263, "s": 23834, "text": "Use a stack to store all the left elements corresponding to a node to the point that the node is the leftmost node itself. After this, store all the left of the right of the leftmost node in the stack. Then, until and unless the stack is empty, point the next of the current node to the topmost element of the stack and if the topmost element of the node has a right node, store all the left element of the right of the topmost." }, { "code": null, "e": 24267, "s": 24263, "text": "C++" }, { "code": null, "e": 24272, "s": 24267, "text": "Java" }, { "code": null, "e": 24280, "s": 24272, "text": "Python3" }, { "code": null, "e": 24283, "s": 24280, "text": "C#" }, { "code": "#include <iostream>#include <stack>using namespace std; struct Node { int data; struct Node* left; struct Node* right; struct Node* next; Node(int x) { data = x; left = NULL; right = NULL; next = NULL; }}; Node* inorder(Node* root){ if (root->left == NULL) return root; inorder(root->left);} void populateNext(Node* root){ stack<Node*> s; Node* temp = root; while (temp->left) { s.push(temp); temp = temp->left; } Node* curr = temp; if (curr->right) { Node* q = curr->right; while (q) { s.push(q); q = q->left; } } while (!s.empty()) { Node* inorder = s.top(); s.pop(); curr->next = inorder; if (inorder->right) { Node* q = inorder->right; while (q) { s.push(q); q = q->left; } } curr = inorder; }} Node* newnode(int data){ Node* node = new Node(data); return (node);} int main(){ /* Constructed binary tree is 10 / \\ 8 12 / 3 */ Node* root = newnode(10); root->left = newnode(8); root->right = newnode(12); root->left->left = newnode(3); populateNext(root); Node* ptr = inorder(root); while (ptr) { // -1 is printed if there is no successor cout << \"Next of \" << ptr->data << \" is \" << (ptr->next ? ptr->next->data : -1) << endl; ptr = ptr->next; } return 0;}", "e": 25837, "s": 24283, "text": null }, { "code": "import java.util.*; class GFG{ static class Node { int data; Node left; Node right; Node next; Node(int x) { data = x; left = null; right = null; next = null; } }; static Node inorder(Node root) { if (root.left == null) return root; root = inorder(root.left); return root; } static void populateNext(Node root) { Stack<Node> s = new Stack<>(); Node temp = root; while (temp.left!=null) { s.add(temp); temp = temp.left; } Node curr = temp; if (curr.right!=null) { Node q = curr.right; while (q!=null) { s.add(q); q = q.left; } } while (!s.isEmpty()) { Node inorder = s.peek(); s.pop(); curr.next = inorder; if (inorder.right!=null) { Node q = inorder.right; while (q!=null) { s.add(q); q = q.left; } } curr = inorder; } } static Node newnode(int data) { Node node = new Node(data); return (node); } public static void main(String[] args) { /* Constructed binary tree is 10 / \\ 8 12 / 3 */ Node root = newnode(10); root.left = newnode(8); root.right = newnode(12); root.left.left = newnode(3); populateNext(root); Node ptr = inorder(root); while (ptr != null) { // -1 is printed if there is no successor System.out.print(\"Next of \" + ptr.data+ \" is \" + (ptr.next!=null ? ptr.next.data : -1) +\"\\n\"); ptr = ptr.next; } }} // This code is contributed by Rajput-Ji", "e": 27458, "s": 25837, "text": null }, { "code": "class GFG: class Node: data = 0 left = None right = None next = None def __init__(self, x): self.data = x self.left = None self.right = None self.next = None @staticmethod def inorder(root): if (root.left == None): return root root = GFG.inorder(root.left) return root @staticmethod def populateNext(root): s = [] temp = root while (temp.left != None): s.append(temp) temp = temp.left curr = temp if (curr.right != None): q = curr.right while (q != None): s.append(q) q = q.left while (not (len(s) == 0)): inorder = s[-1] s.pop() curr.next = inorder if (inorder.right != None): q = inorder.right while (q != None): s.append(q) q = q.left curr = inorder @staticmethod def newnode(data): node = GFG.Node(data) return (node) @staticmethod def main(args): # Constructed binary tree is # 10 # / \\ # 8 12 # / # 3 root = GFG.newnode(10) root.left = GFG.newnode(8) root.right = GFG.newnode(12) root.left.left = GFG.newnode(3) GFG.populateNext(root) ptr = GFG.inorder(root) while (ptr != None): # -1 is printed if there is no successor print(\"Next of \" + str(ptr.data) + \" is \" + str((ptr.next.data if ptr.next != None else -1)) + \"\\n\", end=\"\") ptr = ptr.next if __name__ == \"__main__\": GFG.main([]) # This code is contributed by mukulsomukesh", "e": 29299, "s": 27458, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG { public class Node { public int data; public Node left; public Node right; public Node next; public Node(int x) { data = x; left = null; right = null; next = null; } }; static Node inorder(Node root) { if (root.left == null) return root; root = inorder(root.left); return root; } static void populateNext(Node root) { Stack<Node> s = new Stack<Node>(); Node temp = root; while (temp.left != null) { s.Push(temp); temp = temp.left; } Node curr = temp; if (curr.right != null) { Node q = curr.right; while (q != null) { s.Push(q); q = q.left; } } while (s.Count!=0) { Node inorder = s.Peek(); s.Pop(); curr.next = inorder; if (inorder.right != null) { Node q = inorder.right; while (q != null) { s.Push(q); q = q.left; } } curr = inorder; } } static Node newnode(int data) { Node node = new Node(data); return (node); } public static void Main(String[] args) { /* * Constructed binary tree is 10 / \\ 8 12 / 3 */ Node root = newnode(10); root.left = newnode(8); root.right = newnode(12); root.left.left = newnode(3); populateNext(root); Node ptr = inorder(root); while (ptr != null) { // -1 is printed if there is no successor Console.Write(\"Next of \" + ptr.data + \" is \" + (ptr.next != null ? ptr.next.data : -1) + \"\\n\"); ptr = ptr.next; } }} // This code contributed by Rajput-Ji", "e": 31221, "s": 29299, "text": null }, { "code": null, "e": 31286, "s": 31221, "text": "Next of 3 is 8\nNext of 8 is 10\nNext of 10 is 12\nNext of 12 is -1" }, { "code": null, "e": 31307, "s": 31286, "text": "Complexity Analysis:" }, { "code": null, "e": 31376, "s": 31307, "text": "Time Complexity: O(n), where n is the number of nodes in the tree. " }, { "code": null, "e": 31436, "s": 31376, "text": "Space Complexity: O(h), where h is the height of the tree. " }, { "code": null, "e": 31698, "s": 31436, "text": "This approach is better because it overcomes the auxiliary stack space complexity in the recursive method and the space complexity in the arrayList method because the stack will at most store the number of elements equal to height of the tree at any given time." }, { "code": null, "e": 31709, "s": 31698, "text": "andrew1234" }, { "code": null, "e": 31723, "s": 31709, "text": "rathbhupendra" }, { "code": null, "e": 31737, "s": 31723, "text": "princiraj1992" }, { "code": null, "e": 31751, "s": 31737, "text": "shubham_singh" }, { "code": null, "e": 31764, "s": 31751, "text": "Akanksha_Rai" }, { "code": null, "e": 31779, "s": 31764, "text": "mohit kumar 29" }, { "code": null, "e": 31791, "s": 31779, "text": "unknown2108" }, { "code": null, "e": 31802, "s": 31791, "text": "avllikhita" }, { "code": null, "e": 31814, "s": 31802, "text": "importantly" }, { "code": null, "e": 31835, "s": 31814, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31845, "s": 31835, "text": "kalrap615" }, { "code": null, "e": 31859, "s": 31845, "text": "GauravRajput1" }, { "code": null, "e": 31875, "s": 31859, "text": "simranarora5sos" }, { "code": null, "e": 31884, "s": 31875, "text": "sweetyty" }, { "code": null, "e": 31899, "s": 31884, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 31912, "s": 31899, "text": "simmytarika5" }, { "code": null, "e": 31922, "s": 31912, "text": "Rajput-Ji" }, { "code": null, "e": 31935, "s": 31922, "text": "sharmakavi59" }, { "code": null, "e": 31949, "s": 31935, "text": "mukulsomukesh" }, { "code": null, "e": 31954, "s": 31949, "text": "Tree" }, { "code": null, "e": 31959, "s": 31954, "text": "Tree" } ]
Find a way to fill matrix with 1’s and 0’s in blank positions
31 May, 2022 Given an N * M matrix mat[][] which consists of two types of characters ‘.’ and ‘_’. The task is to fill the matrix in positions where it contains ‘.’ with 1‘s and 0‘s. Fill the matrix in such a way that no two adjacent cells contain the same number and print the modified matrix.Examples: Input: mat[][] = {{‘.’, ‘_’}, {‘_’, ‘.’}} Output: 1 _ _ 1Input: mat[][] = {{‘_’, ‘_’}, {‘_’, ‘_’}} Output: _ _ _ _ There is no place to fill the numbers. Approach: An efficient approach is to fill the matrix in the following pattern: 10101010... 01010101... 10101010... skipping ‘_’ characters whenever encountered.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 2#define M 2 // Function to generate and// print the required matrixvoid Matrix(char a[N][M]){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; cout << a[i][j] << " "; } cout << endl; // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver codeint main(){ char a[N][M] = { { '.', '_' }, { '_', '.' } }; Matrix(a); return 0;} // Java implementation of the approachimport java.io.*; class GFG{ static int N = 2;static int M = 2; // Function to generate and// print the required matrixstatic void Matrix(char a[][]){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; System.out.print( a[i][j] + " "); } System.out.println(); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver code public static void main (String[] args) { char a[][] = { { '.', '_' }, { '_', '.' } }; Matrix(a); }} // This code is contributed by anuj_67.. # Python3 implementation of the approach N = 2M = 2 # Function to generate and# print the required matrixdef Matrix(a) : ch = '1'; for i in range(N) : for j in range(M) : # Replace the '.' if (a[i][j] == '.') : a[i][j] = ch; # Toggle number if (ch == '1') : ch == '0' else : ch = '1' print(a[i][j],end = " "); print() # For each row, change # the starting number if (i % 2 == 0) : ch = '0'; else : ch = '1'; # Driver codeif __name__ == "__main__" : a = [ [ '.', '_' ], [ '_', '.' ], ] Matrix(a); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ static int N = 2;static int M = 2; // Function to generate and// print the required matrixstatic void Matrix(char [,]a){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i,j] == '.') a[i,j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; Console.Write( a[i,j] + " "); } Console.WriteLine(); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver codepublic static void Main (String[] args){ char [,]a = { { '.', '_' }, { '_', '.' } }; Matrix(a);}} // This code has been contributed by 29AjayKumar <script> // Javascript implementation of the approach const N = 2;const M = 2; // Function to generate and// print the required matrixfunction Matrix(a){ let ch = '1'; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; document.write(a[i][j] + " "); } document.write("<br>"); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver code let a = [ [ '.', '_' ], [ '_', '.' ] ]; Matrix(a); </script> 1 _ _ 1 Time Complexity : O(N*M) Auxiliary Space: O(1) vt_m 29AjayKumar ankthon souravmahato348 rishav1329 Competitive Programming Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Bitwise Hacks for Competitive Programming Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 320, "s": 28, "text": "Given an N * M matrix mat[][] which consists of two types of characters ‘.’ and ‘_’. The task is to fill the matrix in positions where it contains ‘.’ with 1‘s and 0‘s. Fill the matrix in such a way that no two adjacent cells contain the same number and print the modified matrix.Examples: " }, { "code": null, "e": 476, "s": 320, "text": "Input: mat[][] = {{‘.’, ‘_’}, {‘_’, ‘.’}} Output: 1 _ _ 1Input: mat[][] = {{‘_’, ‘_’}, {‘_’, ‘_’}} Output: _ _ _ _ There is no place to fill the numbers. " }, { "code": null, "e": 560, "s": 478, "text": "Approach: An efficient approach is to fill the matrix in the following pattern: " }, { "code": null, "e": 598, "s": 560, "text": "10101010... 01010101... 10101010... " }, { "code": null, "e": 696, "s": 598, "text": "skipping ‘_’ characters whenever encountered.Below is the implementation of the above approach: " }, { "code": null, "e": 700, "s": 696, "text": "C++" }, { "code": null, "e": 705, "s": 700, "text": "Java" }, { "code": null, "e": 713, "s": 705, "text": "Python3" }, { "code": null, "e": 716, "s": 713, "text": "C#" }, { "code": null, "e": 727, "s": 716, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 2#define M 2 // Function to generate and// print the required matrixvoid Matrix(char a[N][M]){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; cout << a[i][j] << \" \"; } cout << endl; // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver codeint main(){ char a[N][M] = { { '.', '_' }, { '_', '.' } }; Matrix(a); return 0;}", "e": 1500, "s": 727, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ static int N = 2;static int M = 2; // Function to generate and// print the required matrixstatic void Matrix(char a[][]){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; System.out.print( a[i][j] + \" \"); } System.out.println(); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver code public static void main (String[] args) { char a[][] = { { '.', '_' }, { '_', '.' } }; Matrix(a); }} // This code is contributed by anuj_67..", "e": 2382, "s": 1500, "text": null }, { "code": "# Python3 implementation of the approach N = 2M = 2 # Function to generate and# print the required matrixdef Matrix(a) : ch = '1'; for i in range(N) : for j in range(M) : # Replace the '.' if (a[i][j] == '.') : a[i][j] = ch; # Toggle number if (ch == '1') : ch == '0' else : ch = '1' print(a[i][j],end = \" \"); print() # For each row, change # the starting number if (i % 2 == 0) : ch = '0'; else : ch = '1'; # Driver codeif __name__ == \"__main__\" : a = [ [ '.', '_' ], [ '_', '.' ], ] Matrix(a); # This code is contributed by AnkitRai01", "e": 3159, "s": 2382, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int N = 2;static int M = 2; // Function to generate and// print the required matrixstatic void Matrix(char [,]a){ char ch = '1'; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // Replace the '.' if (a[i,j] == '.') a[i,j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; Console.Write( a[i,j] + \" \"); } Console.WriteLine(); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver codepublic static void Main (String[] args){ char [,]a = { { '.', '_' }, { '_', '.' } }; Matrix(a);}} // This code has been contributed by 29AjayKumar", "e": 4010, "s": 3159, "text": null }, { "code": "<script> // Javascript implementation of the approach const N = 2;const M = 2; // Function to generate and// print the required matrixfunction Matrix(a){ let ch = '1'; for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // Replace the '.' if (a[i][j] == '.') a[i][j] = ch; // Toggle number ch = (ch == '1') ? '0' : '1'; document.write(a[i][j] + \" \"); } document.write(\"<br>\"); // For each row, change // the starting number if (i % 2 == 0) ch = '0'; else ch = '1'; }} // Driver code let a = [ [ '.', '_' ], [ '_', '.' ] ]; Matrix(a); </script>", "e": 4744, "s": 4010, "text": null }, { "code": null, "e": 4753, "s": 4744, "text": "1 _ \n_ 1" }, { "code": null, "e": 4780, "s": 4755, "text": "Time Complexity : O(N*M)" }, { "code": null, "e": 4802, "s": 4780, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4807, "s": 4802, "text": "vt_m" }, { "code": null, "e": 4819, "s": 4807, "text": "29AjayKumar" }, { "code": null, "e": 4827, "s": 4819, "text": "ankthon" }, { "code": null, "e": 4843, "s": 4827, "text": "souravmahato348" }, { "code": null, "e": 4854, "s": 4843, "text": "rishav1329" }, { "code": null, "e": 4878, "s": 4854, "text": "Competitive Programming" }, { "code": null, "e": 4891, "s": 4878, "text": "Mathematical" }, { "code": null, "e": 4898, "s": 4891, "text": "Matrix" }, { "code": null, "e": 4911, "s": 4898, "text": "Mathematical" }, { "code": null, "e": 4918, "s": 4911, "text": "Matrix" }, { "code": null, "e": 5016, "s": 4918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5043, "s": 5016, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 5121, "s": 5043, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 5159, "s": 5121, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 5218, "s": 5159, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 5260, "s": 5218, "text": "Bitwise Hacks for Competitive Programming" }, { "code": null, "e": 5290, "s": 5260, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5333, "s": 5290, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5393, "s": 5333, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5408, "s": 5393, "text": "C++ Data Types" } ]
Creating Custom Widgets in PyQt5
11 May, 2020 PyQt5 is one of the most advanced GUI library for Python. While being powerful, it’s also well structured and makes it easy for you to build ‘advanced’ items. Custom widgets in PyQt5 is a breeze. The below has a well-described way of building custom Widgets with PyQt5, The Main WindowLet’s start by creating our main window. We go the OOP route right from the start. An OOP-less way is a pain for maintenance. Our skeleton looks like this import sys from PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGui class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) if __name__ == '__main__': app = QtWidgets.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_()) which outputs to A Normal App Let’s add a textbox and a label that just echoes whatever we type.Our main window turns to this: class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text()) which outputs to Widget Skeleton An empty widget looks like this: class MyWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout) Let’s name it as EchoText and add what we added to our main window class EchoText(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text()) Using Like A Normal Widget In our main window, leave only the skeleton and add the following: self.echotext_widget = EchoText() self.layout.addWidget(self.echotext_widget) and it gets displayed as when we coded everything in the main window itself. The Complete App Here’s the complete code for the entire application import sys from PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGui class EchoText(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text()) class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) self.echotext_widget = EchoText() self.layout.addWidget(self.echotext_widget) if __name__ == '__main__': app = QtWidgets.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_()) Try creating a different widget and adding it. PyQt5 sounds tougher than Tkinter to get started but it’s worth it! Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2020" }, { "code": null, "e": 248, "s": 52, "text": "PyQt5 is one of the most advanced GUI library for Python. While being powerful, it’s also well structured and makes it easy for you to build ‘advanced’ items. Custom widgets in PyQt5 is a breeze." }, { "code": null, "e": 322, "s": 248, "text": "The below has a well-described way of building custom Widgets with PyQt5," }, { "code": null, "e": 492, "s": 322, "text": "The Main WindowLet’s start by creating our main window. We go the OOP route right from the start. An OOP-less way is a pain for maintenance. Our skeleton looks like this" }, { "code": "import sys from PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGui class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) if __name__ == '__main__': app = QtWidgets.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_())", "e": 1054, "s": 492, "text": null }, { "code": null, "e": 1071, "s": 1054, "text": "which outputs to" }, { "code": null, "e": 1084, "s": 1071, "text": "A Normal App" }, { "code": null, "e": 1181, "s": 1084, "text": "Let’s add a textbox and a label that just echoes whatever we type.Our main window turns to this:" }, { "code": "class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text())", "e": 1863, "s": 1181, "text": null }, { "code": null, "e": 1880, "s": 1863, "text": "which outputs to" }, { "code": null, "e": 1896, "s": 1880, "text": "Widget Skeleton" }, { "code": null, "e": 1929, "s": 1896, "text": "An empty widget looks like this:" }, { "code": "class MyWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout)", "e": 2127, "s": 1929, "text": null }, { "code": null, "e": 2194, "s": 2127, "text": "Let’s name it as EchoText and add what we added to our main window" }, { "code": "class EchoText(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text())", "e": 2745, "s": 2194, "text": null }, { "code": null, "e": 2772, "s": 2745, "text": "Using Like A Normal Widget" }, { "code": null, "e": 2839, "s": 2772, "text": "In our main window, leave only the skeleton and add the following:" }, { "code": "self.echotext_widget = EchoText() self.layout.addWidget(self.echotext_widget)", "e": 2918, "s": 2839, "text": null }, { "code": null, "e": 2995, "s": 2918, "text": "and it gets displayed as when we coded everything in the main window itself." }, { "code": null, "e": 3012, "s": 2995, "text": "The Complete App" }, { "code": null, "e": 3064, "s": 3012, "text": "Here’s the complete code for the entire application" }, { "code": "import sys from PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGui class EchoText(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.layout = QtWidgets.QGridLayout() self.setLayout(self.layout) self.textbox = QtWidgets.QLineEdit() self.echo_label = QtWidgets.QLabel('') self.textbox.textChanged.connect(self.textbox_text_changed) self.layout.addWidget(self.textbox, 0, 0) self.layout.addWidget(self.echo_label, 1, 0) def textbox_text_changed(self): self.echo_label.setText(self.textbox.text()) class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.init_gui() def init_gui(self): self.window = QtWidgets.QWidget() self.layout = QtWidgets.QGridLayout() self.setCentralWidget(self.window) self.window.setLayout(self.layout) self.echotext_widget = EchoText() self.layout.addWidget(self.echotext_widget) if __name__ == '__main__': app = QtWidgets.QApplication([]) win = MainWindow() win.show() sys.exit(app.exec_())", "e": 4262, "s": 3064, "text": null }, { "code": null, "e": 4377, "s": 4262, "text": "Try creating a different widget and adding it. PyQt5 sounds tougher than Tkinter to get started but it’s worth it!" }, { "code": null, "e": 4388, "s": 4377, "text": "Python-gui" }, { "code": null, "e": 4400, "s": 4388, "text": "Python-PyQt" }, { "code": null, "e": 4407, "s": 4400, "text": "Python" }, { "code": null, "e": 4505, "s": 4407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4547, "s": 4505, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4569, "s": 4547, "text": "Enumerate() in Python" }, { "code": null, "e": 4595, "s": 4569, "text": "Python String | replace()" }, { "code": null, "e": 4627, "s": 4595, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4656, "s": 4627, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4683, "s": 4656, "text": "Python Classes and Objects" }, { "code": null, "e": 4704, "s": 4683, "text": "Python OOPs Concepts" }, { "code": null, "e": 4740, "s": 4704, "text": "Convert integer to string in Python" }, { "code": null, "e": 4763, "s": 4740, "text": "Introduction To PYTHON" } ]
React-Bootstrap Accordion Component
18 May, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. Accordion Component provides a way to control our card components so that we can open them one at a time. We can use the following approach in ReactJS to use the react-bootstrap Accordion Component. Accordion Props: activeKey: It is the currently active key which corresponds to the expanded card which is currently active. as: It can be used as a custom element type for this component. defaultActiveKey: It is the default active key that expands on start. onSelect: It is the callback function named as SelectCallback. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Accordion.Toggle Props: as: It can be used as a custom element type for this component. eventKey: It is a key that is used to correspond to the collapse component when the click is triggered on this component. onClick: It is the callback function that is triggered when this component is clicked. Accordion.Collapse Props: children: It is used to pass the children’s prop which should contain only a single child. eventKey: It is a key that is used to correspond to the toggler. useAccordionToggle Props: It is used to create our custom toggle component with this hook. eventKey: It is the key that is given for the specified element/card. callback: It is a callback function that is triggered on a toggle event. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import 'bootstrap/dist/css/bootstrap.css'; import Accordion from 'react-bootstrap/Accordion';import Card from 'react-bootstrap/Card';import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Accordion Component</h4> <Accordion defaultActiveKey="0"> <Card> <Card.Header> <Accordion.Toggle as={Button} variant="link" eventKey="0"> Click Me to Toggle! </Accordion.Toggle> </Card.Header> <Accordion.Collapse eventKey="0"> <Card.Body> Greetings from GeeksforGeeks </Card.Body> </Accordion.Collapse> </Card> </Accordion> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/accordion/ React-Bootstrap JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2021" }, { "code": null, "e": 309, "s": 28, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Accordion Component provides a way to control our card components so that we can open them one at a time. We can use the following approach in ReactJS to use the react-bootstrap Accordion Component." }, { "code": null, "e": 326, "s": 309, "text": "Accordion Props:" }, { "code": null, "e": 434, "s": 326, "text": "activeKey: It is the currently active key which corresponds to the expanded card which is currently active." }, { "code": null, "e": 498, "s": 434, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 568, "s": 498, "text": "defaultActiveKey: It is the default active key that expands on start." }, { "code": null, "e": 631, "s": 568, "text": "onSelect: It is the callback function named as SelectCallback." }, { "code": null, "e": 715, "s": 631, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 739, "s": 715, "text": "Accordion.Toggle Props:" }, { "code": null, "e": 803, "s": 739, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 925, "s": 803, "text": "eventKey: It is a key that is used to correspond to the collapse component when the click is triggered on this component." }, { "code": null, "e": 1012, "s": 925, "text": "onClick: It is the callback function that is triggered when this component is clicked." }, { "code": null, "e": 1038, "s": 1012, "text": "Accordion.Collapse Props:" }, { "code": null, "e": 1129, "s": 1038, "text": "children: It is used to pass the children’s prop which should contain only a single child." }, { "code": null, "e": 1194, "s": 1129, "text": "eventKey: It is a key that is used to correspond to the toggler." }, { "code": null, "e": 1286, "s": 1194, "text": "useAccordionToggle Props: It is used to create our custom toggle component with this hook. " }, { "code": null, "e": 1356, "s": 1286, "text": "eventKey: It is the key that is given for the specified element/card." }, { "code": null, "e": 1429, "s": 1356, "text": "callback: It is a callback function that is triggered on a toggle event." }, { "code": null, "e": 1479, "s": 1429, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 1574, "s": 1479, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 1638, "s": 1574, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1670, "s": 1638, "text": "npx create-react-app foldername" }, { "code": null, "e": 1784, "s": 1670, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername" }, { "code": null, "e": 1885, "s": 1784, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:" }, { "code": null, "e": 1899, "s": 1885, "text": "cd foldername" }, { "code": null, "e": 2054, "s": 1899, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 2159, "s": 2054, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 2210, "s": 2159, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 2262, "s": 2210, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 2280, "s": 2262, "text": "Project Structure" }, { "code": null, "e": 2410, "s": 2280, "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": 2417, "s": 2410, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css'; import Accordion from 'react-bootstrap/Accordion';import Card from 'react-bootstrap/Card';import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Accordion Component</h4> <Accordion defaultActiveKey=\"0\"> <Card> <Card.Header> <Accordion.Toggle as={Button} variant=\"link\" eventKey=\"0\"> Click Me to Toggle! </Accordion.Toggle> </Card.Header> <Accordion.Collapse eventKey=\"0\"> <Card.Body> Greetings from GeeksforGeeks </Card.Body> </Accordion.Collapse> </Card> </Accordion> </div> );}", "e": 3253, "s": 2417, "text": null }, { "code": null, "e": 3366, "s": 3253, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 3376, "s": 3366, "text": "npm start" }, { "code": null, "e": 3475, "s": 3376, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3542, "s": 3475, "text": "Reference: https://react-bootstrap.github.io/components/accordion/" }, { "code": null, "e": 3558, "s": 3542, "text": "React-Bootstrap" }, { "code": null, "e": 3569, "s": 3558, "text": "JavaScript" }, { "code": null, "e": 3577, "s": 3569, "text": "ReactJS" }, { "code": null, "e": 3594, "s": 3577, "text": "Web Technologies" }, { "code": null, "e": 3692, "s": 3594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3753, "s": 3692, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3793, "s": 3753, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3834, "s": 3793, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3876, "s": 3834, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3898, "s": 3876, "text": "JavaScript | Promises" }, { "code": null, "e": 3941, "s": 3898, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3986, "s": 3941, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 4024, "s": 3986, "text": "Axios in React: A Guide for Beginners" } ]
Deepl – Command Line Language Translator Tool for Linux
14 Feb, 2021 Deepl is the best language translator command-line tool that detects the language of input text and translates it into the desired language using advanced machine learning and neural networking algorithms. It is open source and powered by a German tech Company under the MIT license. It supports the following languages English (EN) Italian (IT) Spanish (ES) Polish (PL) French (FR) German (DE) Dutch (NL) It also provides a paid subscription for the interested user and also has a free version (Deepl — CLI Translator Tool). This article will discuss the installation steps of the Deepl — CLI Translator Tool and the use of this Tool with some examples. Note: we will see a screenshot of only Ubuntu Linux Machine cause all Linux versions has similarity in installation process run all these command same as Ubuntu. Step 1: Install the latest version of the Node.Js or If you have already installed then check the version of Node.js and it should be > 6.0 Step 2: Install Yarn package dependency manager in Linux Distribution For different Linux distribution Run different Following Commands. For Ubuntu: curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list sudo apt update && sudo apt install yarn yarn --version For Centos / Fedora / RHEL: curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo curl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash - yum install yarn [On CentOS/RHEL Linux distribution ] dnf install yarn [On Fedora Linux distribution ] yarn --version For Gentoo Linux: sudo emerge --ask sys-apps/yarn yarn --version Step 3: Now, Install Deepl – CLI Translator Tool yarn global add deepl-translator-cli Step 4: Check Installation deepl --version or ./yarn/bin/deepl --version To Translate the text: deepl translate -t '${ target_language_ISO_code }' '${ Input_string }' To detect the language: deepl detect '${ target_language_ISO_code }' '${ Input_string } To get a better understanding you can see the following drawing: Example: Command: deepl translate -t ‘DE’ ‘geeks for geeks is the best site’ Output : ‘geeks für geeks ist die beste Seite’ Explanation : Here given above command has three part Initial Command Syntax to translate → deepl translate -t target language ISO code → ‘DE’ (for german)Sentence that you want to translate → ‘geeks for geeks is the best site’ Initial Command Syntax to translate → deepl translate -t target language ISO code → ‘DE’ (for german) Sentence that you want to translate → ‘geeks for geeks is the best site’ Command : deepl detect ‘geeks for geeks is the best site’ Output : English(EN) Explanation : Here given above command has only two part Initial Command Syntax to translate → deepl detectSentence for that you want to detect language → ‘geeks for geeks is the best site’ Initial Command Syntax to translate → deepl detect Sentence for that you want to detect language → ‘geeks for geeks is the best site’ Linux-Tools Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2021" }, { "code": null, "e": 312, "s": 28, "text": "Deepl is the best language translator command-line tool that detects the language of input text and translates it into the desired language using advanced machine learning and neural networking algorithms. It is open source and powered by a German tech Company under the MIT license." }, { "code": null, "e": 349, "s": 312, "text": "It supports the following languages " }, { "code": null, "e": 362, "s": 349, "text": "English (EN)" }, { "code": null, "e": 375, "s": 362, "text": "Italian (IT)" }, { "code": null, "e": 388, "s": 375, "text": "Spanish (ES)" }, { "code": null, "e": 400, "s": 388, "text": "Polish (PL)" }, { "code": null, "e": 412, "s": 400, "text": "French (FR)" }, { "code": null, "e": 424, "s": 412, "text": "German (DE)" }, { "code": null, "e": 435, "s": 424, "text": "Dutch (NL)" }, { "code": null, "e": 685, "s": 435, "text": "It also provides a paid subscription for the interested user and also has a free version (Deepl — CLI Translator Tool). This article will discuss the installation steps of the Deepl — CLI Translator Tool and the use of this Tool with some examples. " }, { "code": null, "e": 847, "s": 685, "text": "Note: we will see a screenshot of only Ubuntu Linux Machine cause all Linux versions has similarity in installation process run all these command same as Ubuntu." }, { "code": null, "e": 987, "s": 847, "text": "Step 1: Install the latest version of the Node.Js or If you have already installed then check the version of Node.js and it should be > 6.0" }, { "code": null, "e": 1057, "s": 987, "text": "Step 2: Install Yarn package dependency manager in Linux Distribution" }, { "code": null, "e": 1124, "s": 1057, "text": "For different Linux distribution Run different Following Commands." }, { "code": null, "e": 1136, "s": 1124, "text": "For Ubuntu:" }, { "code": null, "e": 1363, "s": 1136, "text": "curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\necho \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list\nsudo apt update && sudo apt install yarn\nyarn --version " }, { "code": null, "e": 1391, "s": 1363, "text": "For Centos / Fedora / RHEL:" }, { "code": null, "e": 1689, "s": 1391, "text": "curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo\ncurl --silent --location https://rpm.nodesource.com/setup_12.x | sudo bash -\nyum install yarn [On CentOS/RHEL Linux distribution ]\ndnf install yarn [On Fedora Linux distribution ]\nyarn --version " }, { "code": null, "e": 1707, "s": 1689, "text": "For Gentoo Linux:" }, { "code": null, "e": 1755, "s": 1707, "text": "sudo emerge --ask sys-apps/yarn\nyarn --version " }, { "code": null, "e": 1804, "s": 1755, "text": "Step 3: Now, Install Deepl – CLI Translator Tool" }, { "code": null, "e": 1842, "s": 1804, "text": " yarn global add deepl-translator-cli" }, { "code": null, "e": 1869, "s": 1842, "text": "Step 4: Check Installation" }, { "code": null, "e": 1918, "s": 1869, "text": "deepl --version \nor\n./yarn/bin/deepl --version " }, { "code": null, "e": 1941, "s": 1918, "text": "To Translate the text:" }, { "code": null, "e": 2014, "s": 1941, "text": "deepl translate -t '${ target_language_ISO_code }' '${ Input_string }'" }, { "code": null, "e": 2038, "s": 2014, "text": "To detect the language:" }, { "code": null, "e": 2104, "s": 2038, "text": "deepl detect '${ target_language_ISO_code }' '${ Input_string }" }, { "code": null, "e": 2169, "s": 2104, "text": "To get a better understanding you can see the following drawing:" }, { "code": null, "e": 2178, "s": 2169, "text": "Example:" }, { "code": null, "e": 2246, "s": 2178, "text": "Command: deepl translate -t ‘DE’ ‘geeks for geeks is the best site’" }, { "code": null, "e": 2294, "s": 2246, "text": "Output : ‘geeks für geeks ist die beste Seite’" }, { "code": null, "e": 2349, "s": 2294, "text": "Explanation : Here given above command has three part " }, { "code": null, "e": 2523, "s": 2349, "text": "Initial Command Syntax to translate → deepl translate -t target language ISO code → ‘DE’ (for german)Sentence that you want to translate → ‘geeks for geeks is the best site’" }, { "code": null, "e": 2581, "s": 2523, "text": "Initial Command Syntax to translate → deepl translate -t " }, { "code": null, "e": 2626, "s": 2581, "text": "target language ISO code → ‘DE’ (for german)" }, { "code": null, "e": 2699, "s": 2626, "text": "Sentence that you want to translate → ‘geeks for geeks is the best site’" }, { "code": null, "e": 2757, "s": 2699, "text": "Command : deepl detect ‘geeks for geeks is the best site’" }, { "code": null, "e": 2778, "s": 2757, "text": "Output : English(EN)" }, { "code": null, "e": 2835, "s": 2778, "text": "Explanation : Here given above command has only two part" }, { "code": null, "e": 2968, "s": 2835, "text": "Initial Command Syntax to translate → deepl detectSentence for that you want to detect language → ‘geeks for geeks is the best site’" }, { "code": null, "e": 3019, "s": 2968, "text": "Initial Command Syntax to translate → deepl detect" }, { "code": null, "e": 3102, "s": 3019, "text": "Sentence for that you want to detect language → ‘geeks for geeks is the best site’" }, { "code": null, "e": 3114, "s": 3102, "text": "Linux-Tools" }, { "code": null, "e": 3121, "s": 3114, "text": "Picked" }, { "code": null, "e": 3132, "s": 3121, "text": "Linux-Unix" } ]
PostgreSQL - LIMIT Clause
The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECT statement. The basic syntax of SELECT statement with LIMIT clause is as follows − SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] The following is the syntax of LIMIT clause when it is used along with OFFSET clause − SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] OFFSET [row num] LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated by the rest of the query. Consider the table COMPANY having records as follows − # select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows) The following is an example, which limits the row in the table according to the number of rows you want to fetch from table − testdb=# SELECT * FROM COMPANY LIMIT 4; This would produce the following result − id | name | age | address | salary ----+-------+-----+-------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 (4 rows) However, in certain situation, you may need to pick up a set of records from a particular offset. Here is an example, which picks up three records starting from the third position − testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2; This would produce the following result − id | name | age | address | salary ----+-------+-----+-----------+-------- 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000
[ { "code": null, "e": 3055, "s": 2959, "text": "The PostgreSQL LIMIT clause is used to limit the data amount returned by the SELECT statement." }, { "code": null, "e": 3126, "s": 3055, "text": "The basic syntax of SELECT statement with LIMIT clause is as follows −" }, { "code": null, "e": 3195, "s": 3126, "text": "SELECT column1, column2, columnN\nFROM table_name\nLIMIT [no of rows]\n" }, { "code": null, "e": 3282, "s": 3195, "text": "The following is the syntax of LIMIT clause when it is used along with OFFSET clause −" }, { "code": null, "e": 3368, "s": 3282, "text": "SELECT column1, column2, columnN\nFROM table_name\nLIMIT [no of rows] OFFSET [row num]\n" }, { "code": null, "e": 3479, "s": 3368, "text": "LIMIT and OFFSET allow you to retrieve just a portion of the rows that are generated by the rest of the query." }, { "code": null, "e": 3534, "s": 3479, "text": "Consider the table COMPANY having records as follows −" }, { "code": null, "e": 3920, "s": 3534, "text": "# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)" }, { "code": null, "e": 4046, "s": 3920, "text": "The following is an example, which limits the row in the table according to the number of rows you want to fetch from table −" }, { "code": null, "e": 4086, "s": 4046, "text": "testdb=# SELECT * FROM COMPANY LIMIT 4;" }, { "code": null, "e": 4128, "s": 4086, "text": "This would produce the following result −" }, { "code": null, "e": 4385, "s": 4128, "text": " id | name | age | address | salary\n----+-------+-----+-------------+--------\n 1 | Paul | 32 | California | 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n(4 rows)\n" }, { "code": null, "e": 4567, "s": 4385, "text": "However, in certain situation, you may need to pick up a set of records from a particular offset. Here is an example, which picks up three records starting from the third position −" }, { "code": null, "e": 4616, "s": 4567, "text": "testdb=# SELECT * FROM COMPANY LIMIT 3 OFFSET 2;" }, { "code": null, "e": 4658, "s": 4616, "text": "This would produce the following result −" } ]
Box plot in R using ggplot2
15 Dec, 2021 In this article, we are going to create a Boxplot with various functionality in R programming language using the ggplot2 package. For data distributions, you may require more information than central tendency values (median, mean, mode). To analyze data variability, you need to know how dispersed the data are. Well, a Box plot is a graph that illustrates the distribution of values in data. Box plots are commonly used to show the distribution of data in a standard way by presenting five summary values. The list below summarizes the minimum, Q1 (First Quartile), median, Q3 (Third Quartile), and maximum values. Summarizing these values can provide us with information about our outliers and their values. In ggplot2, geom_boxplot() is used to create a boxplot. Syntax: geom_boxplot( mapping = NULL, data = NULL, stat = “identity”, position = “identity”, ..., outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, notch = FALSE,na.rm = FALSE, show.legend = FALSE, inherit.aes = FALSE) Dataset in use: Crop_recommendation Let us first create a regular boxplot, for that we first have to import all the required libraries and dataset in use. Then simply put all the attributes to plot by in ggplot() function along with geom_boxplot. Example: R library(ggplot2) # Create the dataset or load the dataset # for the chartDataset <- c(17, 32, 8, 53, 1,45,56,678,23,34)Dataset # loading data set and storing it in ds variableds <- read.csv( "c://crop//archive//Crop_recommendation.csv", header = TRUE) # create a boxplot by using geom_boxplot() function# of ggplot2 packagecrop=ggplot(data=ds, mapping=aes(x=label, y=temperature))+geom_boxplot()crop Output: Mean value can also be added to a boxplot, for that we have to specify the function we are using, within stat_summary(). This function is used to add new summary values and add these summary values to the plot. By using this function you don’t need to calculate the mean values before plotting. Syntax: stat_summary( fun, geom) Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( "c://crop//archive//Crop_recommendation.csv", header = TRUE) # add mean to ggplot2 boxplotggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + stat_summary(fun = "mean", geom = "point", shape = 8, size = 2, color = "white") Output: Now let us discuss the legend position in Boxplot using theme() function. We can change the legend position to top or bottom, or you can remove the legend position in a boxplot. It is possible to customize plot components such as titles, labels, fonts, background, gridlines, and legends by using themes. Plots can be customized by using themes. You can modify the theme of a single plot using the theme() method or you can modify the active theme, which will affect all subsequent plots, by calling theme_update(). Syntax: theme( line, rect, text, title, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, ......, validate = TRUE) On this function, if you set legend.position argument to either top or bottom the position will change. Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # change the legend position in R using ggplot2ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + theme(legend.position = "top") Output: Boxplots can also be placed horizontally using coord_flip() function. This function just switches the x and y-axis. Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Creating a Horizontal Boxplot using ggplot2 in Rggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + coord_flip() Output: 1) default Use the command color=label to add color to the outline of the bars. Syntax: color=label Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( "c://crop//archive//Crop_recommendation.csv", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2 Output: 2) Manually Using custom color palettes: To use custom color palettes, use the scale_color_manual() function, and within this function provide outline color for each boxplot. Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2 # Now, it is also possible to change line colors manuallycrop2+scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9","#999999","Red", "green","yellow")) Output: Using brewer color palettes: You can change the outline color of the boxplot with brewer color palettes. For doing so you just need to use the scale_color_brewer() function and set the palette argument within this function. Syntax: scale_color_brewer(palette) Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( "c://crop//archive//Crop_recommendation.csv", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2 # for Using brewer color palettescrop2+scale_color_brewer(palette="Dark2") Output: Using grayscale: To use grayscale color palette you need to use scale_color_grey() function, and add theme_classic() function to it. Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot() # for using grey scalecrop2 + scale_color_grey() + theme_classic() Output: 1) Default: For filling the boxplot with your choice of color then you can use the fill attribute command to add colors inside the geom_boxplot() function. The fill will be under geom_boxplot( ) as it is variable in this case. Syntax: fill=’color’ Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Now fill the boxplot with choice of your colorcrop1=ggplot(data=ds, mapping=aes(x=label, y=temperature))+geom_boxplot(fill='green')crop1 Output: For filling the boxplot color by default you just need to include fill attribute in aes() function within ggplot(). The fill will be inside aes( ) under ggplot( ) as it is variable in this case. Syntax: fill=label Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Change Colors of a ggplot2 Boxplot in R crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2) Output: 2) Manually: If you want to change boxplot colors manually then you can use three functions scale_fill_manual(), scale_fill_brewer() and scale_fill_grey() according to your choice. Using custom color palettes: To use custom color palettes scale_fill_manual() function is used and values of colors as an argument. Syntax: scale_fill_manual(values) Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( "c://crop//archive//Crop_recommendation.csv", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2) crop3+scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9", "#999999","Red","green","yellow")) Output: Using brewer color palettes: To use brewer color palettes scale_fill_brewer() from RColorBrewer package and palette as an argument Syntax: scale_fill_brewer(palette) Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2) crop3+scale_fill_brewer(palette="Dark1") Output: Using grayscale: To fill color of boxplots with grayscale use scale_fill_grey() with theme_classic(). Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour="black", outlier.shape=16, outlier.size=2) # for using grey scalecrop3 + scale_fill_grey() + theme_classic() Output: Jitters are very useful to handle over-plotting problems caused by discrete datasets. You can also adjust the positions of the jitters too and for doing so you just need to set the position attribute within geom_jitter(). You can also change shape, size of a dot by using the size and shape argument in ggplot jitter. Syntax: geom_jitter(mapping = NULL, data = NULL, stat = “identity”, position = “jitter”, ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot()+ geom_jitter(position=position_jitter(0.2)) Output: For adding notch boxplot you just need to set the notch attribute as TRUE within geom_boxplot(). Example: R library(ggplot2) # loading data set and storing it in ds variableds <- read.csv("c://crop//archive//Crop_recommendation.csv", header = TRUE) # Add notched box plotggplot(ds, aes(x=label, y=temperature)) + geom_boxplot(notch = TRUE)+ geom_jitter(position=position_jitter(0.2)) Output: gabaa406 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Dec, 2021" }, { "code": null, "e": 183, "s": 52, "text": "In this article, we are going to create a Boxplot with various functionality in R programming language using the ggplot2 package. " }, { "code": null, "e": 766, "s": 183, "text": "For data distributions, you may require more information than central tendency values (median, mean, mode). To analyze data variability, you need to know how dispersed the data are. Well, a Box plot is a graph that illustrates the distribution of values in data. Box plots are commonly used to show the distribution of data in a standard way by presenting five summary values. The list below summarizes the minimum, Q1 (First Quartile), median, Q3 (Third Quartile), and maximum values. Summarizing these values can provide us with information about our outliers and their values. " }, { "code": null, "e": 822, "s": 766, "text": "In ggplot2, geom_boxplot() is used to create a boxplot." }, { "code": null, "e": 1097, "s": 822, "text": "Syntax: geom_boxplot( mapping = NULL, data = NULL, stat = “identity”, position = “identity”, ..., outlier.colour = NULL, outlier.color = NULL, outlier.fill = NULL, outlier.shape = 19, outlier.size = 1.5, notch = FALSE,na.rm = FALSE, show.legend = FALSE, inherit.aes = FALSE)" }, { "code": null, "e": 1133, "s": 1097, "text": "Dataset in use: Crop_recommendation" }, { "code": null, "e": 1344, "s": 1133, "text": "Let us first create a regular boxplot, for that we first have to import all the required libraries and dataset in use. Then simply put all the attributes to plot by in ggplot() function along with geom_boxplot." }, { "code": null, "e": 1353, "s": 1344, "text": "Example:" }, { "code": null, "e": 1355, "s": 1353, "text": "R" }, { "code": "library(ggplot2) # Create the dataset or load the dataset # for the chartDataset <- c(17, 32, 8, 53, 1,45,56,678,23,34)Dataset # loading data set and storing it in ds variableds <- read.csv( \"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # create a boxplot by using geom_boxplot() function# of ggplot2 packagecrop=ggplot(data=ds, mapping=aes(x=label, y=temperature))+geom_boxplot()crop", "e": 1759, "s": 1355, "text": null }, { "code": null, "e": 1769, "s": 1759, "text": " Output: " }, { "code": null, "e": 2064, "s": 1769, "text": "Mean value can also be added to a boxplot, for that we have to specify the function we are using, within stat_summary(). This function is used to add new summary values and add these summary values to the plot. By using this function you don’t need to calculate the mean values before plotting." }, { "code": null, "e": 2073, "s": 2064, "text": "Syntax: " }, { "code": null, "e": 2098, "s": 2073, "text": "stat_summary( fun, geom)" }, { "code": null, "e": 2107, "s": 2098, "text": "Example:" }, { "code": null, "e": 2109, "s": 2107, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( \"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # add mean to ggplot2 boxplotggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + stat_summary(fun = \"mean\", geom = \"point\", shape = 8, size = 2, color = \"white\")", "e": 2458, "s": 2109, "text": null }, { "code": null, "e": 2466, "s": 2458, "text": "Output:" }, { "code": null, "e": 2982, "s": 2466, "text": "Now let us discuss the legend position in Boxplot using theme() function. We can change the legend position to top or bottom, or you can remove the legend position in a boxplot. It is possible to customize plot components such as titles, labels, fonts, background, gridlines, and legends by using themes. Plots can be customized by using themes. You can modify the theme of a single plot using the theme() method or you can modify the active theme, which will affect all subsequent plots, by calling theme_update()." }, { "code": null, "e": 2990, "s": 2982, "text": "Syntax:" }, { "code": null, "e": 3271, "s": 2990, "text": "theme( line, rect, text, title, aspect.ratio, axis.title, axis.title.x, axis.title.x.top, axis.title.x.bottom, axis.title.y, axis.title.y.left, axis.title.y.right, axis.text, axis.text.x, axis.text.x.top, axis.text.x.bottom, axis.text.y, axis.text.y.left, ......, validate = TRUE)" }, { "code": null, "e": 3375, "s": 3271, "text": "On this function, if you set legend.position argument to either top or bottom the position will change." }, { "code": null, "e": 3384, "s": 3375, "text": "Example:" }, { "code": null, "e": 3386, "s": 3384, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # change the legend position in R using ggplot2ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + theme(legend.position = \"top\")", "e": 3687, "s": 3386, "text": null }, { "code": null, "e": 3695, "s": 3687, "text": "Output:" }, { "code": null, "e": 3811, "s": 3695, "text": "Boxplots can also be placed horizontally using coord_flip() function. This function just switches the x and y-axis." }, { "code": null, "e": 3820, "s": 3811, "text": "Example:" }, { "code": null, "e": 3822, "s": 3820, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Creating a Horizontal Boxplot using ggplot2 in Rggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot() + coord_flip()", "e": 4108, "s": 3822, "text": null }, { "code": null, "e": 4116, "s": 4108, "text": "Output:" }, { "code": null, "e": 4127, "s": 4116, "text": "1) default" }, { "code": null, "e": 4197, "s": 4127, "text": "Use the command color=label to add color to the outline of the bars. " }, { "code": null, "e": 4205, "s": 4197, "text": "Syntax:" }, { "code": null, "e": 4217, "s": 4205, "text": "color=label" }, { "code": null, "e": 4226, "s": 4217, "text": "Example:" }, { "code": null, "e": 4228, "s": 4226, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( \"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2", "e": 4495, "s": 4228, "text": null }, { "code": null, "e": 4503, "s": 4495, "text": "Output:" }, { "code": null, "e": 4515, "s": 4503, "text": "2) Manually" }, { "code": null, "e": 4678, "s": 4515, "text": "Using custom color palettes: To use custom color palettes, use the scale_color_manual() function, and within this function provide outline color for each boxplot." }, { "code": null, "e": 4687, "s": 4678, "text": "Example:" }, { "code": null, "e": 4689, "s": 4687, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2 # Now, it is also possible to change line colors manuallycrop2+scale_color_manual(values=c(\"#999999\", \"#E69F00\", \"#56B4E9\",\"#999999\",\"Red\", \"green\",\"yellow\"))", "e": 5182, "s": 4689, "text": null }, { "code": null, "e": 5190, "s": 5182, "text": "Output:" }, { "code": null, "e": 5415, "s": 5190, "text": "Using brewer color palettes: You can change the outline color of the boxplot with brewer color palettes. For doing so you just need to use the scale_color_brewer() function and set the palette argument within this function. " }, { "code": null, "e": 5423, "s": 5415, "text": "Syntax:" }, { "code": null, "e": 5451, "s": 5423, "text": "scale_color_brewer(palette)" }, { "code": null, "e": 5460, "s": 5451, "text": "Example:" }, { "code": null, "e": 5462, "s": 5460, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( \"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot()crop2 # for Using brewer color palettescrop2+scale_color_brewer(palette=\"Dark2\")", "e": 5805, "s": 5462, "text": null }, { "code": null, "e": 5813, "s": 5805, "text": "Output:" }, { "code": null, "e": 5946, "s": 5813, "text": "Using grayscale: To use grayscale color palette you need to use scale_color_grey() function, and add theme_classic() function to it." }, { "code": null, "e": 5955, "s": 5946, "text": "Example:" }, { "code": null, "e": 5957, "s": 5955, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Change box plot line colors by groupscrop2<-ggplot(ds, aes(x=label, y=temperature, color=label)) + geom_boxplot() # for using grey scalecrop2 + scale_color_grey() + theme_classic()", "e": 6285, "s": 5957, "text": null }, { "code": null, "e": 6293, "s": 6285, "text": "Output:" }, { "code": null, "e": 6520, "s": 6293, "text": "1) Default: For filling the boxplot with your choice of color then you can use the fill attribute command to add colors inside the geom_boxplot() function. The fill will be under geom_boxplot( ) as it is variable in this case." }, { "code": null, "e": 6528, "s": 6520, "text": "Syntax:" }, { "code": null, "e": 6541, "s": 6528, "text": "fill=’color’" }, { "code": null, "e": 6550, "s": 6541, "text": "Example:" }, { "code": null, "e": 6552, "s": 6550, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Now fill the boxplot with choice of your colorcrop1=ggplot(data=ds, mapping=aes(x=label, y=temperature))+geom_boxplot(fill='green')crop1", "e": 6834, "s": 6552, "text": null }, { "code": null, "e": 6842, "s": 6834, "text": "Output:" }, { "code": null, "e": 7037, "s": 6842, "text": "For filling the boxplot color by default you just need to include fill attribute in aes() function within ggplot(). The fill will be inside aes( ) under ggplot( ) as it is variable in this case." }, { "code": null, "e": 7045, "s": 7037, "text": "Syntax:" }, { "code": null, "e": 7056, "s": 7045, "text": "fill=label" }, { "code": null, "e": 7065, "s": 7056, "text": "Example:" }, { "code": null, "e": 7067, "s": 7065, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Change Colors of a ggplot2 Boxplot in R crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2)", "e": 7392, "s": 7067, "text": null }, { "code": null, "e": 7400, "s": 7392, "text": "Output:" }, { "code": null, "e": 7581, "s": 7400, "text": "2) Manually: If you want to change boxplot colors manually then you can use three functions scale_fill_manual(), scale_fill_brewer() and scale_fill_grey() according to your choice." }, { "code": null, "e": 7713, "s": 7581, "text": "Using custom color palettes: To use custom color palettes scale_fill_manual() function is used and values of colors as an argument." }, { "code": null, "e": 7721, "s": 7713, "text": "Syntax:" }, { "code": null, "e": 7747, "s": 7721, "text": "scale_fill_manual(values)" }, { "code": null, "e": 7756, "s": 7747, "text": "Example:" }, { "code": null, "e": 7758, "s": 7756, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv( \"c://crop//archive//Crop_recommendation.csv\", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2) crop3+scale_fill_manual(values=c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#999999\",\"Red\",\"green\",\"yellow\"))", "e": 8177, "s": 7758, "text": null }, { "code": null, "e": 8185, "s": 8177, "text": "Output:" }, { "code": null, "e": 8316, "s": 8185, "text": "Using brewer color palettes: To use brewer color palettes scale_fill_brewer() from RColorBrewer package and palette as an argument" }, { "code": null, "e": 8324, "s": 8316, "text": "Syntax:" }, { "code": null, "e": 8351, "s": 8324, "text": "scale_fill_brewer(palette)" }, { "code": null, "e": 8360, "s": 8351, "text": "Example:" }, { "code": null, "e": 8362, "s": 8360, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2) crop3+scale_fill_brewer(palette=\"Dark1\")", "e": 8687, "s": 8362, "text": null }, { "code": null, "e": 8695, "s": 8687, "text": "Output:" }, { "code": null, "e": 8797, "s": 8695, "text": "Using grayscale: To fill color of boxplots with grayscale use scale_fill_grey() with theme_classic()." }, { "code": null, "e": 8806, "s": 8797, "text": "Example:" }, { "code": null, "e": 8808, "s": 8806, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) crop3<-ggplot(ds, aes(x = label, y = temperature, fill = label)) + geom_boxplot(outlier.colour=\"black\", outlier.shape=16, outlier.size=2) # for using grey scalecrop3 + scale_fill_grey() + theme_classic()", "e": 9158, "s": 8808, "text": null }, { "code": null, "e": 9166, "s": 9158, "text": "Output:" }, { "code": null, "e": 9484, "s": 9166, "text": "Jitters are very useful to handle over-plotting problems caused by discrete datasets. You can also adjust the positions of the jitters too and for doing so you just need to set the position attribute within geom_jitter(). You can also change shape, size of a dot by using the size and shape argument in ggplot jitter." }, { "code": null, "e": 9492, "s": 9484, "text": "Syntax:" }, { "code": null, "e": 9660, "s": 9492, "text": "geom_jitter(mapping = NULL, data = NULL, stat = “identity”, position = “jitter”, ..., width = NULL, height = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE)" }, { "code": null, "e": 9669, "s": 9660, "text": "Example:" }, { "code": null, "e": 9671, "s": 9669, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) ggplot(ds, aes(x=label, y=temperature)) + geom_boxplot()+ geom_jitter(position=position_jitter(0.2))", "e": 9918, "s": 9671, "text": null }, { "code": null, "e": 9926, "s": 9918, "text": "Output:" }, { "code": null, "e": 10023, "s": 9926, "text": "For adding notch boxplot you just need to set the notch attribute as TRUE within geom_boxplot()." }, { "code": null, "e": 10032, "s": 10023, "text": "Example:" }, { "code": null, "e": 10034, "s": 10032, "text": "R" }, { "code": "library(ggplot2) # loading data set and storing it in ds variableds <- read.csv(\"c://crop//archive//Crop_recommendation.csv\", header = TRUE) # Add notched box plotggplot(ds, aes(x=label, y=temperature)) + geom_boxplot(notch = TRUE)+ geom_jitter(position=position_jitter(0.2))", "e": 10315, "s": 10034, "text": null }, { "code": null, "e": 10323, "s": 10315, "text": "Output:" }, { "code": null, "e": 10332, "s": 10323, "text": "gabaa406" }, { "code": null, "e": 10339, "s": 10332, "text": "Picked" }, { "code": null, "e": 10348, "s": 10339, "text": "R-ggplot" }, { "code": null, "e": 10359, "s": 10348, "text": "R Language" }, { "code": null, "e": 10457, "s": 10359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10509, "s": 10457, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 10567, "s": 10509, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 10602, "s": 10567, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 10640, "s": 10602, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 10657, "s": 10640, "text": "R - if statement" }, { "code": null, "e": 10694, "s": 10657, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 10743, "s": 10694, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 10786, "s": 10743, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 10823, "s": 10786, "text": "How to import an Excel File into R ?" } ]
CSS Box model
11 Oct, 2021 The CSS box model is a container that contains multiple properties including borders, margin, padding, and the content itself. It is used to create the design and layout of web pages. It can be used as a toolkit for customizing the layout of different elements. The web browser renders every element as a rectangular box according to the CSS box model. Box-Model has multiple properties in CSS. Some of them are given below: content: This property is used to displays the text, images, etc, that can be sized using the width & height property. padding: This property is used to create space around the element, inside any defined border. border: This property is used to cover the content & any padding, & also allows to set the style, color, and width of the border. margin: This property is used to create space around the element ie., around the border area. The following figure illustrates the Box model in CSS. Content Area: This area consists of content like text, images, or other media content. It is bounded by the content edge and its dimensions are given by content-box width and height. Padding Area: It includes the element’s padding. This area is actually the space around the content area and within the border-box. Its dimensions are given by the width of the padding-box and the height of the padding-box. Border Area: It is the area between the box’s padding and margin. Its dimensions are given by the width and height of the border. Margin Area: This area consists of space between border and margin. The dimensions of the Margin area are the margin-box width and the margin-box height. It is useful to separate the element from its neighbors. For setting the width & height property of an element(for properly rendering the content in the browser), we need to understand the working of the CSS Box model. While setting the width and height properties of an element with CSS, we have only set the width and height of the content area. We need to add padding, borders, and margins in order to calculate the full size of an element. Consider the below example. p { width: 80px; height: 70px; margin: 0; border: 2px solid black; padding: 5px; } The total width for the element can be calculated as: Total element width = width + left padding + right padding + left border + right border + left margin + right margin The <p> element can have a total width of 94px. Total width = 80px (width) + 10px (left padding + right padding) + 4px (left border + right border) + 0px (left margin + right margin) = 94px. The total height for the element can be calculated as: Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin The <p> element can have a total height of 84px. Total height = 70px (height) + 10px (top padding + bottom padding) + 4px (top border + bottom border) + 0px (top margin + bottom margin) = 84px. We will understand the Box model concept through the examples. Example 1: This example illustrates the use of the CSS Box model for aligning & displaying it properly. HTML <!DOCTYPE html><head> <title>CSS Box Model</title> <style> .main { font-size: 36px; font-weight: bold; Text-align: center; } .gfg { margin-left: 60px; border: 50px solid #009900; width: 300px; height: 200px; text-align: center; padding: 50px; } .gfg1 { font-size: 42px; font-weight: bold; color: #009900; margin-top: 60px; background-color: #c5c5db; } .gfg2 { font-size: 18px; font-weight: bold; background-color: #c5c5db; } </style></head> <body> <div class="main">CSS Box-Model Property</div> <div class="gfg"> <div class="gfg1">GeeksforGeeks</div> <div class="gfg2"> A computer science portal for geeks </div> </div></body></html> Output: Example 2: This example illustrates the Box Model by implementing the various properties. HTML <!DOCTYPE html><head> <style> .main { font-size: 32px; font-weight: bold; text-align: center; } #box { padding-top: 40px; width: 400px; height: 100px; border: 50px solid green; margin: 50px; text-align: center; font-size: 32px; font-weight: bold; } </style></head> <body> <div class="main">CSS Box-Model Property</div> <div id="box">GeeksforGeeks</div></body></html> Output: Supported Browser: Google Chrome Internet Explorer Microsoft Edge Firefox Opera Safari ysachin2314 bhaskargeeksforgeeks CSS-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2021" }, { "code": null, "e": 480, "s": 54, "text": "The CSS box model is a container that contains multiple properties including borders, margin, padding, and the content itself. It is used to create the design and layout of web pages. It can be used as a toolkit for customizing the layout of different elements. The web browser renders every element as a rectangular box according to the CSS box model. Box-Model has multiple properties in CSS. Some of them are given below: " }, { "code": null, "e": 599, "s": 480, "text": "content: This property is used to displays the text, images, etc, that can be sized using the width & height property." }, { "code": null, "e": 693, "s": 599, "text": "padding: This property is used to create space around the element, inside any defined border." }, { "code": null, "e": 823, "s": 693, "text": "border: This property is used to cover the content & any padding, & also allows to set the style, color, and width of the border." }, { "code": null, "e": 917, "s": 823, "text": "margin: This property is used to create space around the element ie., around the border area." }, { "code": null, "e": 972, "s": 917, "text": "The following figure illustrates the Box model in CSS." }, { "code": null, "e": 1155, "s": 972, "text": "Content Area: This area consists of content like text, images, or other media content. It is bounded by the content edge and its dimensions are given by content-box width and height." }, { "code": null, "e": 1379, "s": 1155, "text": "Padding Area: It includes the element’s padding. This area is actually the space around the content area and within the border-box. Its dimensions are given by the width of the padding-box and the height of the padding-box." }, { "code": null, "e": 1509, "s": 1379, "text": "Border Area: It is the area between the box’s padding and margin. Its dimensions are given by the width and height of the border." }, { "code": null, "e": 1720, "s": 1509, "text": "Margin Area: This area consists of space between border and margin. The dimensions of the Margin area are the margin-box width and the margin-box height. It is useful to separate the element from its neighbors." }, { "code": null, "e": 1882, "s": 1720, "text": "For setting the width & height property of an element(for properly rendering the content in the browser), we need to understand the working of the CSS Box model." }, { "code": null, "e": 2135, "s": 1882, "text": "While setting the width and height properties of an element with CSS, we have only set the width and height of the content area. We need to add padding, borders, and margins in order to calculate the full size of an element. Consider the below example." }, { "code": null, "e": 2223, "s": 2135, "text": "p {\n width: 80px;\n height: 70px;\n margin: 0;\n border: 2px solid black;\n padding: 5px;\n}" }, { "code": null, "e": 2277, "s": 2223, "text": "The total width for the element can be calculated as:" }, { "code": null, "e": 2394, "s": 2277, "text": "Total element width = width + left padding + right padding + left border + right border + left margin + right margin" }, { "code": null, "e": 2442, "s": 2394, "text": "The <p> element can have a total width of 94px." }, { "code": null, "e": 2585, "s": 2442, "text": "Total width = 80px (width) + 10px (left padding + right padding) + 4px (left border + right border) + 0px (left margin + right margin) = 94px." }, { "code": null, "e": 2640, "s": 2585, "text": "The total height for the element can be calculated as:" }, { "code": null, "e": 2759, "s": 2640, "text": "Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin" }, { "code": null, "e": 2808, "s": 2759, "text": "The <p> element can have a total height of 84px." }, { "code": null, "e": 2953, "s": 2808, "text": "Total height = 70px (height) + 10px (top padding + bottom padding) + 4px (top border + bottom border) + 0px (top margin + bottom margin) = 84px." }, { "code": null, "e": 3016, "s": 2953, "text": "We will understand the Box model concept through the examples." }, { "code": null, "e": 3120, "s": 3016, "text": "Example 1: This example illustrates the use of the CSS Box model for aligning & displaying it properly." }, { "code": null, "e": 3125, "s": 3120, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <title>CSS Box Model</title> <style> .main { font-size: 36px; font-weight: bold; Text-align: center; } .gfg { margin-left: 60px; border: 50px solid #009900; width: 300px; height: 200px; text-align: center; padding: 50px; } .gfg1 { font-size: 42px; font-weight: bold; color: #009900; margin-top: 60px; background-color: #c5c5db; } .gfg2 { font-size: 18px; font-weight: bold; background-color: #c5c5db; } </style></head> <body> <div class=\"main\">CSS Box-Model Property</div> <div class=\"gfg\"> <div class=\"gfg1\">GeeksforGeeks</div> <div class=\"gfg2\"> A computer science portal for geeks </div> </div></body></html>", "e": 3971, "s": 3125, "text": null }, { "code": null, "e": 3979, "s": 3971, "text": "Output:" }, { "code": null, "e": 4069, "s": 3979, "text": "Example 2: This example illustrates the Box Model by implementing the various properties." }, { "code": null, "e": 4074, "s": 4069, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <style> .main { font-size: 32px; font-weight: bold; text-align: center; } #box { padding-top: 40px; width: 400px; height: 100px; border: 50px solid green; margin: 50px; text-align: center; font-size: 32px; font-weight: bold; } </style></head> <body> <div class=\"main\">CSS Box-Model Property</div> <div id=\"box\">GeeksforGeeks</div></body></html>", "e": 4549, "s": 4074, "text": null }, { "code": null, "e": 4557, "s": 4549, "text": "Output:" }, { "code": null, "e": 4576, "s": 4557, "text": "Supported Browser:" }, { "code": null, "e": 4590, "s": 4576, "text": "Google Chrome" }, { "code": null, "e": 4608, "s": 4590, "text": "Internet Explorer" }, { "code": null, "e": 4623, "s": 4608, "text": "Microsoft Edge" }, { "code": null, "e": 4631, "s": 4623, "text": "Firefox" }, { "code": null, "e": 4637, "s": 4631, "text": "Opera" }, { "code": null, "e": 4644, "s": 4637, "text": "Safari" }, { "code": null, "e": 4656, "s": 4644, "text": "ysachin2314" }, { "code": null, "e": 4677, "s": 4656, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4688, "s": 4677, "text": "CSS-Basics" }, { "code": null, "e": 4692, "s": 4688, "text": "CSS" }, { "code": null, "e": 4697, "s": 4692, "text": "HTML" }, { "code": null, "e": 4714, "s": 4697, "text": "Web Technologies" }, { "code": null, "e": 4719, "s": 4714, "text": "HTML" }, { "code": null, "e": 4817, "s": 4719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4865, "s": 4817, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4927, "s": 4865, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4977, "s": 4927, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5035, "s": 4977, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 5085, "s": 5035, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 5133, "s": 5085, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5195, "s": 5133, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5245, "s": 5195, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5269, "s": 5245, "text": "REST API (Introduction)" } ]
Python – Invoking Functions with and without Parentheses
08 May, 2020 Functions in Python are the defined blocks of code that perform a specific task. In this section, we will discuss the difference in invoking functions with and without Parentheses. When we call a function with parentheses, the function gets execute and returns the result to the callable. In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself. Let’s discuss 3 important concepts: Invoking functions Return functions Passing functions The below function performs a simple task, string concatenation. Here we will invoke the function `concatenate_string` with and without parentheses and see the difference. def concatenate_string(*args): string1 = args[0] string2 = args[1] return string1 + string2 obj = concatenate_string('Hello, ', 'George')print('Function call with Parentheses: ')print(obj) obj = concatenate_stringprint('Function call without Parentheses: ')print(obj) Output Function call with Parentheses: Hello, George Function call without Parentheses: <function concatenate_string at 0x7f0bb991df28> For the first case, when we call concatenate_string('Hello, ', 'George'), the function executes and returns the concatenated string.And, for the second case, when we call concatenate_string i.e. without parentheses, a reference is passed to the callable rather than executing the function itself. Here the callable can decide what to do with the reference. From the above discussion you can understand that, when the function is called with parentheses, the code is executed and returns the result. And, when it is called without parentheses, a function reference is returned to the callable.So, what happens when a function is coded along with a return statement with parentheses and without parentheses. Let’s go through an example. With Parentheses def concatenate_string(*args): string1 = args[0] string2 = args[1] def merge_string(string1, string2): return string1 + string2 return merge_string(string1, string2) def func(): conc_obj = concatenate_string('Hello, ', 'George') print(conc_obj) func() Output Hello, George From the above example, it’s clear that the merge_string is a function within the function concatenate_string and the main function (concatenate_string) returns the sub-function (merge_string) to the caller. return merge_string(string1, string2) Here merge_string is invoked with parentheses, hence it executes and provides the result to the concatenate_string from where the result is passed to func. Without Parentheses def concatenate_string(): def merge_string(string1, string2): return string1 + string2 return merge_string def func(): # return the reference of merge_string func conc_obj = concatenate_string() print(conc_obj) # prints the reference # executes the reference print(conc_obj('Hello, ', 'George')) func() Output: <function concatenate_string..merge_string at 0x7f1e54ebc158> Hello, George Since the merge_string is used without parentheses, the concatenate_string passes the function reference to the callable func rather than executing the merge_string. return merge_string Hence, we can conclude that when we code sub-function with parentheses in a return statement, the main function executes the sub-function and passes the result to the callable. And, when we code subfunction without parentheses in a return statement, the main function passes the sub-function reference to the callable rather than executing it. Here the callable decides what to do with the reference. You can pass a function as an argument by creating the reference, calling the function without parentheses, and provide it as an argument. Let’s look into the code. def concatenate_string(*args): string1 = args[0] string2 = args[1] def merge_string(string1, string2): return string1 + string2 # string merge # executes merge_string and return the result return merge_string(string1, string2) def function_call(function): string1 = 'Hello, ' string2 = 'George' return function(string1, string2) # passing function as argumentprint(function_call(concatenate_string)) Output: Hello, George In this case, the reference of concatenate_string is passed to the function_call as an argument. function_call(concatenate_string) Inside function_call, it executes the concatenate_string using the reference and returns the result to the callable. Python-Functions Articles Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures Difference Between Object And Class SQL | DROP, TRUNCATE Implementation of LinkedList in Javascript Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n08 May, 2020" }, { "code": null, "e": 235, "s": 54, "text": "Functions in Python are the defined blocks of code that perform a specific task. In this section, we will discuss the difference in invoking functions with and without Parentheses." }, { "code": null, "e": 343, "s": 235, "text": "When we call a function with parentheses, the function gets execute and returns the result to the callable." }, { "code": null, "e": 493, "s": 343, "text": "In another case, when we call a function without parentheses, a function reference is sent to the callable rather than executing the function itself." }, { "code": null, "e": 529, "s": 493, "text": "Let’s discuss 3 important concepts:" }, { "code": null, "e": 548, "s": 529, "text": "Invoking functions" }, { "code": null, "e": 565, "s": 548, "text": "Return functions" }, { "code": null, "e": 583, "s": 565, "text": "Passing functions" }, { "code": null, "e": 755, "s": 583, "text": "The below function performs a simple task, string concatenation. Here we will invoke the function `concatenate_string` with and without parentheses and see the difference." }, { "code": "def concatenate_string(*args): string1 = args[0] string2 = args[1] return string1 + string2 obj = concatenate_string('Hello, ', 'George')print('Function call with Parentheses: ')print(obj) obj = concatenate_stringprint('Function call without Parentheses: ')print(obj)", "e": 1036, "s": 755, "text": null }, { "code": null, "e": 1043, "s": 1036, "text": "Output" }, { "code": null, "e": 1174, "s": 1043, "text": "Function call with Parentheses: \nHello, George\nFunction call without Parentheses:\n<function concatenate_string at 0x7f0bb991df28>\n" }, { "code": null, "e": 1531, "s": 1174, "text": "For the first case, when we call concatenate_string('Hello, ', 'George'), the function executes and returns the concatenated string.And, for the second case, when we call concatenate_string i.e. without parentheses, a reference is passed to the callable rather than executing the function itself. Here the callable can decide what to do with the reference." }, { "code": null, "e": 1909, "s": 1531, "text": "From the above discussion you can understand that, when the function is called with parentheses, the code is executed and returns the result. And, when it is called without parentheses, a function reference is returned to the callable.So, what happens when a function is coded along with a return statement with parentheses and without parentheses. Let’s go through an example." }, { "code": null, "e": 1926, "s": 1909, "text": "With Parentheses" }, { "code": "def concatenate_string(*args): string1 = args[0] string2 = args[1] def merge_string(string1, string2): return string1 + string2 return merge_string(string1, string2) def func(): conc_obj = concatenate_string('Hello, ', 'George') print(conc_obj) func()", "e": 2219, "s": 1926, "text": null }, { "code": null, "e": 2226, "s": 2219, "text": "Output" }, { "code": null, "e": 2240, "s": 2226, "text": "Hello, George" }, { "code": null, "e": 2448, "s": 2240, "text": "From the above example, it’s clear that the merge_string is a function within the function concatenate_string and the main function (concatenate_string) returns the sub-function (merge_string) to the caller." }, { "code": null, "e": 2488, "s": 2448, "text": " return merge_string(string1, string2) " }, { "code": null, "e": 2644, "s": 2488, "text": "Here merge_string is invoked with parentheses, hence it executes and provides the result to the concatenate_string from where the result is passed to func." }, { "code": null, "e": 2664, "s": 2644, "text": "Without Parentheses" }, { "code": "def concatenate_string(): def merge_string(string1, string2): return string1 + string2 return merge_string def func(): # return the reference of merge_string func conc_obj = concatenate_string() print(conc_obj) # prints the reference # executes the reference print(conc_obj('Hello, ', 'George')) func()", "e": 3022, "s": 2664, "text": null }, { "code": null, "e": 3030, "s": 3022, "text": "Output:" }, { "code": null, "e": 3107, "s": 3030, "text": "<function concatenate_string..merge_string at 0x7f1e54ebc158>\nHello, George\n" }, { "code": null, "e": 3273, "s": 3107, "text": "Since the merge_string is used without parentheses, the concatenate_string passes the function reference to the callable func rather than executing the merge_string." }, { "code": null, "e": 3293, "s": 3273, "text": "return merge_string" }, { "code": null, "e": 3694, "s": 3293, "text": "Hence, we can conclude that when we code sub-function with parentheses in a return statement, the main function executes the sub-function and passes the result to the callable. And, when we code subfunction without parentheses in a return statement, the main function passes the sub-function reference to the callable rather than executing it. Here the callable decides what to do with the reference." }, { "code": null, "e": 3859, "s": 3694, "text": "You can pass a function as an argument by creating the reference, calling the function without parentheses, and provide it as an argument. Let’s look into the code." }, { "code": "def concatenate_string(*args): string1 = args[0] string2 = args[1] def merge_string(string1, string2): return string1 + string2 # string merge # executes merge_string and return the result return merge_string(string1, string2) def function_call(function): string1 = 'Hello, ' string2 = 'George' return function(string1, string2) # passing function as argumentprint(function_call(concatenate_string)) ", "e": 4302, "s": 3859, "text": null }, { "code": null, "e": 4310, "s": 4302, "text": "Output:" }, { "code": null, "e": 4324, "s": 4310, "text": "Hello, George" }, { "code": null, "e": 4421, "s": 4324, "text": "In this case, the reference of concatenate_string is passed to the function_call as an argument." }, { "code": null, "e": 4455, "s": 4421, "text": "function_call(concatenate_string)" }, { "code": null, "e": 4572, "s": 4455, "text": "Inside function_call, it executes the concatenate_string using the reference and returns the result to the callable." }, { "code": null, "e": 4589, "s": 4572, "text": "Python-Functions" }, { "code": null, "e": 4598, "s": 4589, "text": "Articles" }, { "code": null, "e": 4605, "s": 4598, "text": "Python" }, { "code": null, "e": 4703, "s": 4605, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4729, "s": 4703, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4776, "s": 4729, "text": "Time complexities of different data structures" }, { "code": null, "e": 4812, "s": 4776, "text": "Difference Between Object And Class" }, { "code": null, "e": 4833, "s": 4812, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 4876, "s": 4833, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 4904, "s": 4876, "text": "Read JSON file using Python" }, { "code": null, "e": 4926, "s": 4904, "text": "Python map() function" }, { "code": null, "e": 4976, "s": 4926, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4994, "s": 4976, "text": "Python Dictionary" } ]
Ideological Differences Between Gandhi and Ambedkar
24 Jun, 2022 The depressed classes so-called untouchables were one of the most debatable topics during the 1930s because of discussion on the separate electorate to the depressed classes. Gandhi and Ambedkar both declared themselves the leader of the depressed classes in India. They both shared many ideas, although in many ways they had different beliefs. There is a striking resemblance in symbolism inherent in some of the actions of both individuals. Gandhi who always talked about the unity of the Indian people, showed his beliefs towards Joint Electorates, whereas Ambedkar, who was born in a depressed class and was the victim of untouchability during his life, saw depressed classes as a religious minority in India and advocated the separate electorates and reserved seats in the Imperial Legislative Council at Round Table Conferences. Electorates in one word mean Voters, so anyone who is above 18 yrs of age and eligible to vote in a particular constituency is called Electorates. In a Separate Electorate, a particular seat in a constituency is reserved for a particular community, and people of the community would only context and participate in the election process. Let’s understand this with an example, suppose there is a constituency named Aligarh and it is reserved for a Muslim candidate. so in separate electorates only people belonging to the Muslim community would vote in the election process, while people from other communities would not vote. In Joint Electorate, a particular seat is reserved for a particular community but here people from all communities can vote and participate in the election process. Ex- A constituency named Aligarh is reserved for a Muslim candidate. So in Joint Electorate, people of all communities could vote in the election process unlike only Muslims in a separate electorate. A separate electorate was introduced in the Indian Council Act of 1909, popularly known as Morley-Minto reform, for the first time in the history of India. In this act, Muslims were favored as they were given representation in the areas where their population was very less in comparison to other communities. These areas were reserved for the separate electorates. It was further extended in the Montague-Chelmsford reforms of 1919, where not only the communal electorate of 1909 was continued but it was also extended to other communities like Sikhs, Indian-Christians, Anglo-Indians, and Europeans. Now apart from Muslims, Sikhs, Indian-Christian, Anglo-Indians, etc could also choose their leaders through a separate electorate. The award was also known as Communal Award. On 16th August 1932, British prime minister Ramsay Macdonald announced this award. As per this award Muslims, Europeans, Sikhs, and Harizans were to elect their representative through a separate electorate. The most important thing was the inclusion of Harijans in separate electorates. Harijans were not minorities but rather they were depressed class among Hindus. They were victims of untouchability and poverty. The inclusion of Harijans in the Communal Award was being seen as an attempt to divide the Hindu society under the divide and rule policy of the British. Gandhi, the principal architect of the Indian Freedom Struggle, saw the Communal Award as an attack on Indian unity and nationalism. He thought it was dangerous to both Hinduism and the depressed classes since it handed no answer to the socially downgraded situation of the depressed classes. Once the depressed classes were acted like a different political being, he reasoned, the problem of rescinding untouchability would get undermined, while separate electorates would assure that the untouchables stayed untouchables in everlasting. Gandhi tried the untouchables as an inborn part of Hindu society. Gandhi demanded that the depressed classes be elected through joint if feasible a broad electorate through universal suffrage while expressing no protest to the claim for a larger composition of allocated seats. On September 18, 1932, he fasted indefinitely to insist on his claims. Poona pact was signed between Gandhi and Ambedkar to abandon the idea of separate electorates for the depressed classes. Gandhi named the depressed classes and the untouchables as “Harijan”, Ambedkar denounced it as a clever scheme. Gandhi also renamed the Depressed Classes League to “Harijan Sevak Sangh“. According to Gandhi, the practice of untouchability was a moral stigma on Indian society and wanted it to get blotted out by acts of atonement. B.R. Ambedkar, the principal architect of the constitution of independent India, supported the idea of a separate electorate proposed by the British government. He advocated the theory of separate electorates for the depressed classes in all round table conferences. By signing the Poona act, he abandoned the idea of separate electorates for depressed classes just only because of Gandhi’s fast but later on, he continued to denounce the Poona Pact till 1947. Ambedkar viewed the Untouchables as a religious minority rather than part of the Hindu community, preferring to call them a “political minority” or a “minority by force“. Ambedkar wanted to unravel the matter of untouchability through constitutional laws and approaches. Gandhi, who declared himself as the sole representative of India in the second round table conference, rejected the extension of a separate electorate to the depressed classes. At the same time, Ambedkar attended all three round table conferences and represented the depressed classes, raising the issue of separate electorates for depressed classes in each session. Ambedkar was awarded by the British government in form of the Communal Award. Gandhi rejected the idea of separate electorates mentioned in the Award, as it was an attack on the Hindu religion. Ambedkar who preferred to call the depressed classes a religious minority welcomed the Communal Award. Ambedkar thought the only way to remove the issue of untouchability was through rules and constitutional methods, while Gandhi treated untouchability as a moral stigma in the Hindu religion and will be erased by penance only. nikhatkhan11 akankshaarora2122 History UPSC Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Changes Introduced By Napoleon in the Administrative System Background of Civil Services in India Before 1923 Royal Indian Navy Rebellion - Causes and Significance Role of British Imperial Power in Complicating the Process of Transfer of Power During 1940s Causes And Effects Of The Amboyna Massacre Legal Measures Taken by Government to Empower Consumers Future Perspective For Non-Conventional Sources of Energy In India Key Features of Federalism Scope and Future of Organic Farming With Sustainable Development Role of Caste in Indian Politics
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2022" }, { "code": null, "e": 863, "s": 28, "text": "The depressed classes so-called untouchables were one of the most debatable topics during the 1930s because of discussion on the separate electorate to the depressed classes. Gandhi and Ambedkar both declared themselves the leader of the depressed classes in India. They both shared many ideas, although in many ways they had different beliefs. There is a striking resemblance in symbolism inherent in some of the actions of both individuals. Gandhi who always talked about the unity of the Indian people, showed his beliefs towards Joint Electorates, whereas Ambedkar, who was born in a depressed class and was the victim of untouchability during his life, saw depressed classes as a religious minority in India and advocated the separate electorates and reserved seats in the Imperial Legislative Council at Round Table Conferences." }, { "code": null, "e": 1011, "s": 863, "text": "Electorates in one word mean Voters, so anyone who is above 18 yrs of age and eligible to vote in a particular constituency is called Electorates. " }, { "code": null, "e": 1490, "s": 1011, "text": "In a Separate Electorate, a particular seat in a constituency is reserved for a particular community, and people of the community would only context and participate in the election process. Let’s understand this with an example, suppose there is a constituency named Aligarh and it is reserved for a Muslim candidate. so in separate electorates only people belonging to the Muslim community would vote in the election process, while people from other communities would not vote." }, { "code": null, "e": 1856, "s": 1490, "text": "In Joint Electorate, a particular seat is reserved for a particular community but here people from all communities can vote and participate in the election process. Ex- A constituency named Aligarh is reserved for a Muslim candidate. So in Joint Electorate, people of all communities could vote in the election process unlike only Muslims in a separate electorate. " }, { "code": null, "e": 2590, "s": 1856, "text": "A separate electorate was introduced in the Indian Council Act of 1909, popularly known as Morley-Minto reform, for the first time in the history of India. In this act, Muslims were favored as they were given representation in the areas where their population was very less in comparison to other communities. These areas were reserved for the separate electorates. It was further extended in the Montague-Chelmsford reforms of 1919, where not only the communal electorate of 1909 was continued but it was also extended to other communities like Sikhs, Indian-Christians, Anglo-Indians, and Europeans. Now apart from Muslims, Sikhs, Indian-Christian, Anglo-Indians, etc could also choose their leaders through a separate electorate. " }, { "code": null, "e": 3204, "s": 2590, "text": "The award was also known as Communal Award. On 16th August 1932, British prime minister Ramsay Macdonald announced this award. As per this award Muslims, Europeans, Sikhs, and Harizans were to elect their representative through a separate electorate. The most important thing was the inclusion of Harijans in separate electorates. Harijans were not minorities but rather they were depressed class among Hindus. They were victims of untouchability and poverty. The inclusion of Harijans in the Communal Award was being seen as an attempt to divide the Hindu society under the divide and rule policy of the British." }, { "code": null, "e": 4544, "s": 3204, "text": "Gandhi, the principal architect of the Indian Freedom Struggle, saw the Communal Award as an attack on Indian unity and nationalism. He thought it was dangerous to both Hinduism and the depressed classes since it handed no answer to the socially downgraded situation of the depressed classes. Once the depressed classes were acted like a different political being, he reasoned, the problem of rescinding untouchability would get undermined, while separate electorates would assure that the untouchables stayed untouchables in everlasting. Gandhi tried the untouchables as an inborn part of Hindu society. Gandhi demanded that the depressed classes be elected through joint if feasible a broad electorate through universal suffrage while expressing no protest to the claim for a larger composition of allocated seats. On September 18, 1932, he fasted indefinitely to insist on his claims. Poona pact was signed between Gandhi and Ambedkar to abandon the idea of separate electorates for the depressed classes. Gandhi named the depressed classes and the untouchables as “Harijan”, Ambedkar denounced it as a clever scheme. Gandhi also renamed the Depressed Classes League to “Harijan Sevak Sangh“. According to Gandhi, the practice of untouchability was a moral stigma on Indian society and wanted it to get blotted out by acts of atonement." }, { "code": null, "e": 5278, "s": 4544, "text": "B.R. Ambedkar, the principal architect of the constitution of independent India, supported the idea of a separate electorate proposed by the British government. He advocated the theory of separate electorates for the depressed classes in all round table conferences. By signing the Poona act, he abandoned the idea of separate electorates for depressed classes just only because of Gandhi’s fast but later on, he continued to denounce the Poona Pact till 1947. Ambedkar viewed the Untouchables as a religious minority rather than part of the Hindu community, preferring to call them a “political minority” or a “minority by force“. Ambedkar wanted to unravel the matter of untouchability through constitutional laws and approaches. " }, { "code": null, "e": 6169, "s": 5278, "text": "Gandhi, who declared himself as the sole representative of India in the second round table conference, rejected the extension of a separate electorate to the depressed classes. At the same time, Ambedkar attended all three round table conferences and represented the depressed classes, raising the issue of separate electorates for depressed classes in each session. Ambedkar was awarded by the British government in form of the Communal Award. Gandhi rejected the idea of separate electorates mentioned in the Award, as it was an attack on the Hindu religion. Ambedkar who preferred to call the depressed classes a religious minority welcomed the Communal Award. Ambedkar thought the only way to remove the issue of untouchability was through rules and constitutional methods, while Gandhi treated untouchability as a moral stigma in the Hindu religion and will be erased by penance only. " }, { "code": null, "e": 6182, "s": 6169, "text": "nikhatkhan11" }, { "code": null, "e": 6200, "s": 6182, "text": "akankshaarora2122" }, { "code": null, "e": 6208, "s": 6200, "text": "History" }, { "code": null, "e": 6213, "s": 6208, "text": "UPSC" }, { "code": null, "e": 6311, "s": 6213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6371, "s": 6311, "text": "Changes Introduced By Napoleon in the Administrative System" }, { "code": null, "e": 6421, "s": 6371, "text": "Background of Civil Services in India Before 1923" }, { "code": null, "e": 6475, "s": 6421, "text": "Royal Indian Navy Rebellion - Causes and Significance" }, { "code": null, "e": 6568, "s": 6475, "text": "Role of British Imperial Power in Complicating the Process of Transfer of Power During 1940s" }, { "code": null, "e": 6611, "s": 6568, "text": "Causes And Effects Of The Amboyna Massacre" }, { "code": null, "e": 6667, "s": 6611, "text": "Legal Measures Taken by Government to Empower Consumers" }, { "code": null, "e": 6734, "s": 6667, "text": "Future Perspective For Non-Conventional Sources of Energy In India" }, { "code": null, "e": 6761, "s": 6734, "text": "Key Features of Federalism" }, { "code": null, "e": 6826, "s": 6761, "text": "Scope and Future of Organic Farming With Sustainable Development" } ]
Difference Between lapply() VS sapply() in R
16 Jan, 2022 A list in R Programming Language can be passed as an argument in lapply() and sapply() functions. It is quite helpful to perform some of the general operations like calculation of sum, cumulative sum, mean, etc of the elements in the objects held by a list. Using “for” loop in R for iterating over a list or vector takes a lot of memory and it is quite slow also. And when it comes to dealing with large data set and iterating over them, for loop is not advised. R provides many alternatives to be applied to lists for looping operations that are pretty useful when working interactively on a command line. lapply() function is one of those functions and it is used to apply a function over a list. Syntax: lapply(List, Operation) Arguments: List: list containing a number of objects Operation: length, sum, mean, and cumsum Return value: Returns a numeric value lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List. lapply(List, sum): Returns the sum of elements held by objects in the list, List. lapply(List, mean): Returns the mean of elements held by objects in the list, List. lapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List. This function is also used to apply a function over a list but with simplified results. Syntax: sapply(List, Operation) Arguments: List: list containing a number of objects Operation: length, sum, mean, and cumsum Return value: Returns a numeric value lapply() function is used with a list and performs operations like: sapply(List, length): Returns the length of objects present in the list, List. sapply(List, sum): Returns the sum of elements held by objects in the list, List. sapply(List, mean): Returns the mean of elements held by objects in the list, List. sapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List. lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects. sapply() function in R is more efficient than lapply() in the output returned because sapply() stores values directly into a vector. Example 1: The lapply() function returns the output as a list whereas sapply() function returns the output as a vector R print("Operations using lapply() function: ") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a = 1: 20, b = 25:30, c = 40:60) # Printing the length of list1 objectslapply(list1, length) # Printing the sum of elements present in the# list1 objectslapply(list1, sum) # Printing the mean of elements present in the# list1 objectslapply(list1, mean) # Printing the cumulative sum of elements# present in the list1 objectslapply(list1, cumsum) print("Operations using sapply() function: ") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data# type)list2 <- list(a = 1: 20, b = 25:30, c = 40:60) # Printing the length of list2 objectssapply(list2, length) # Printing the sum of elements# present in the list2 objectssapply(list2, sum) # Printing the mean of elements# present in the list2 objectssapply(list2, mean) # Printing the cumulative sum# of elements present in the list2 objectssapply(list2, cumsum) Output: Example 2: As you can see in the output, The lapply() function returns the output as a list whereas sapply() function returns the output as a vector. R print("Operations using lapply() function: ") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a=11: 12, sample(c(1, 2, 5, 3), size=4, replace=FALSE), c=40: 60) # Printing the length of list1 objectslapply(list1, length) # Printing the sum of elements present in the# list1 objectslapply(list1, sum) # Printing the mean of elements present in the# list1 objectslapply(list1, mean) # Printing the cumulative sum of elements present# in the list1 objectslapply(list1, cumsum) print("Operations using sapply() function: ") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data type)list2 <- list(a=11: 12, sample(c(1, 2, 5, 3), size=4, replace=FALSE), c=40: 60) # Printing the length of list2 objectssapply(list2, length) # Printing the sum of elements# present in the list2 objectssapply(list2, sum) # Printing the mean of elements# present in the list2 objectssapply(list2, mean) # Printing the cumulative sum of# elements present in the list2 objectssapply(list2, cumsum) Output: Example 3: We can use non-numeric objects also in a list but after applying operations like “mean” on the list we get the “NA” result in output since these operations work for numeric objects only. R print("Operations using lapply() function: ") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects# (same data type)list1 <- list(a = 11: 12, b = c('Geeks', 'for', 'Geeks'), c = 40:60) # Printing the length of list1 objectslapply(list1, length) # Printing the mean of elements# present in the list1 objectslapply(list1, mean) print("Operations using sapply() function: ") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data type)list2 <- list(a = 11: 12, b = c('Geeks', 'for', 'Geeks'), c = 40:60) # Printing the length of list2 objectssapply(list2, length) # Printing the mean of elements# present in the list2 objectssapply(list2, mean) Output: The lapply() and sapply() functions print NA for object b in list1 since b is a non-numeric object. R compiler gives a warning whenever we apply these operations on a list containing a number of non-numeric objects. sapply() function accepts a third argument using which we can return the output as a list instead of a vector. Syntax: sapply(List, Operation, simplify = FALSE) Arguments: List: list containing a number of objects Operation: length, sum, mean, and cumsum simplify = FALSE: Returns the output as a list instead of a vector Return value: Returns a numeric value. R print("Operations using sapply() function: ") # list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a = 11:12, b = 1:10, c = 40:60) # Printing the length of list1 objects as a listsapply(list1, length, simplify = FALSE) # Printing the sum of elements present# in the list1 objects as a listsapply(list1, sum, simplify = FALSE) # Printing the mean of elements present# in the list1 objects as a listsapply(list1, mean, simplify = FALSE) # Printing the cumulative sum of elements# present in the list1 objects as a listsapply(list1, cumsum, simplify = FALSE) Output: As we can see in the output, sapply() function returns the output as a list instead of a vector. So, we can always the third argument to the sapply() function whenever we need to print the output as a list instead of a vector. ruhelaa48 surinderdawra388 Picked R-Functions R-List Difference Between R Language 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 Similarities and Difference between Java and C++ Difference between Compile-time and Run-time Polymorphism in Java Difference between Internal and External fragmentation Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jan, 2022" }, { "code": null, "e": 313, "s": 52, "text": "A list in R Programming Language can be passed as an argument in lapply() and sapply() functions. It is quite helpful to perform some of the general operations like calculation of sum, cumulative sum, mean, etc of the elements in the objects held by a list. " }, { "code": null, "e": 755, "s": 313, "text": "Using “for” loop in R for iterating over a list or vector takes a lot of memory and it is quite slow also. And when it comes to dealing with large data set and iterating over them, for loop is not advised. R provides many alternatives to be applied to lists for looping operations that are pretty useful when working interactively on a command line. lapply() function is one of those functions and it is used to apply a function over a list." }, { "code": null, "e": 787, "s": 755, "text": "Syntax: lapply(List, Operation)" }, { "code": null, "e": 798, "s": 787, "text": "Arguments:" }, { "code": null, "e": 840, "s": 798, "text": "List: list containing a number of objects" }, { "code": null, "e": 881, "s": 840, "text": "Operation: length, sum, mean, and cumsum" }, { "code": null, "e": 919, "s": 881, "text": "Return value: Returns a numeric value" }, { "code": null, "e": 996, "s": 919, "text": "lapply() function is used with a list and performs the following operations:" }, { "code": null, "e": 1075, "s": 996, "text": "lapply(List, length): Returns the length of objects present in the list, List." }, { "code": null, "e": 1157, "s": 1075, "text": "lapply(List, sum): Returns the sum of elements held by objects in the list, List." }, { "code": null, "e": 1241, "s": 1157, "text": "lapply(List, mean): Returns the mean of elements held by objects in the list, List." }, { "code": null, "e": 1349, "s": 1241, "text": "lapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List." }, { "code": null, "e": 1438, "s": 1349, "text": "This function is also used to apply a function over a list but with simplified results. " }, { "code": null, "e": 1470, "s": 1438, "text": "Syntax: sapply(List, Operation)" }, { "code": null, "e": 1481, "s": 1470, "text": "Arguments:" }, { "code": null, "e": 1523, "s": 1481, "text": "List: list containing a number of objects" }, { "code": null, "e": 1564, "s": 1523, "text": "Operation: length, sum, mean, and cumsum" }, { "code": null, "e": 1602, "s": 1564, "text": "Return value: Returns a numeric value" }, { "code": null, "e": 1670, "s": 1602, "text": "lapply() function is used with a list and performs operations like:" }, { "code": null, "e": 1749, "s": 1670, "text": "sapply(List, length): Returns the length of objects present in the list, List." }, { "code": null, "e": 1831, "s": 1749, "text": "sapply(List, sum): Returns the sum of elements held by objects in the list, List." }, { "code": null, "e": 1915, "s": 1831, "text": "sapply(List, mean): Returns the mean of elements held by objects in the list, List." }, { "code": null, "e": 2023, "s": 1915, "text": "sapply(List, cumsum): Returns the cumulative sum of elements held by objects present inside the list, List." }, { "code": null, "e": 2354, "s": 2023, "text": "lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects. sapply() function in R is more efficient than lapply() in the output returned because sapply() stores values directly into a vector. " }, { "code": null, "e": 2474, "s": 2354, "text": "Example 1: The lapply() function returns the output as a list whereas sapply() function returns the output as a vector" }, { "code": null, "e": 2476, "s": 2474, "text": "R" }, { "code": "print(\"Operations using lapply() function: \") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a = 1: 20, b = 25:30, c = 40:60) # Printing the length of list1 objectslapply(list1, length) # Printing the sum of elements present in the# list1 objectslapply(list1, sum) # Printing the mean of elements present in the# list1 objectslapply(list1, mean) # Printing the cumulative sum of elements# present in the list1 objectslapply(list1, cumsum) print(\"Operations using sapply() function: \") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data# type)list2 <- list(a = 1: 20, b = 25:30, c = 40:60) # Printing the length of list2 objectssapply(list2, length) # Printing the sum of elements# present in the list2 objectssapply(list2, sum) # Printing the mean of elements# present in the list2 objectssapply(list2, mean) # Printing the cumulative sum# of elements present in the list2 objectssapply(list2, cumsum)", "e": 3508, "s": 2476, "text": null }, { "code": null, "e": 3517, "s": 3508, "text": "Output: " }, { "code": null, "e": 3668, "s": 3517, "text": "Example 2: As you can see in the output, The lapply() function returns the output as a list whereas sapply() function returns the output as a vector. " }, { "code": null, "e": 3670, "s": 3668, "text": "R" }, { "code": "print(\"Operations using lapply() function: \") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a=11: 12, sample(c(1, 2, 5, 3), size=4, replace=FALSE), c=40: 60) # Printing the length of list1 objectslapply(list1, length) # Printing the sum of elements present in the# list1 objectslapply(list1, sum) # Printing the mean of elements present in the# list1 objectslapply(list1, mean) # Printing the cumulative sum of elements present# in the list1 objectslapply(list1, cumsum) print(\"Operations using sapply() function: \") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data type)list2 <- list(a=11: 12, sample(c(1, 2, 5, 3), size=4, replace=FALSE), c=40: 60) # Printing the length of list2 objectssapply(list2, length) # Printing the sum of elements# present in the list2 objectssapply(list2, sum) # Printing the mean of elements# present in the list2 objectssapply(list2, mean) # Printing the cumulative sum of# elements present in the list2 objectssapply(list2, cumsum)", "e": 4853, "s": 3670, "text": null }, { "code": null, "e": 4861, "s": 4853, "text": "Output:" }, { "code": null, "e": 5059, "s": 4861, "text": "Example 3: We can use non-numeric objects also in a list but after applying operations like “mean” on the list we get the “NA” result in output since these operations work for numeric objects only." }, { "code": null, "e": 5061, "s": 5059, "text": "R" }, { "code": "print(\"Operations using lapply() function: \") # Initializing list1# list1 have three objects a, b, and c# and they all are numeric objects# (same data type)list1 <- list(a = 11: 12, b = c('Geeks', 'for', 'Geeks'), c = 40:60) # Printing the length of list1 objectslapply(list1, length) # Printing the mean of elements# present in the list1 objectslapply(list1, mean) print(\"Operations using sapply() function: \") # Initializing list2# list2 have three objects a, b, and c# and they all are numeric objects (same data type)list2 <- list(a = 11: 12, b = c('Geeks', 'for', 'Geeks'), c = 40:60) # Printing the length of list2 objectssapply(list2, length) # Printing the mean of elements# present in the list2 objectssapply(list2, mean)", "e": 5818, "s": 5061, "text": null }, { "code": null, "e": 5826, "s": 5818, "text": "Output:" }, { "code": null, "e": 6042, "s": 5826, "text": "The lapply() and sapply() functions print NA for object b in list1 since b is a non-numeric object. R compiler gives a warning whenever we apply these operations on a list containing a number of non-numeric objects." }, { "code": null, "e": 6153, "s": 6042, "text": "sapply() function accepts a third argument using which we can return the output as a list instead of a vector." }, { "code": null, "e": 6203, "s": 6153, "text": "Syntax: sapply(List, Operation, simplify = FALSE)" }, { "code": null, "e": 6214, "s": 6203, "text": "Arguments:" }, { "code": null, "e": 6256, "s": 6214, "text": "List: list containing a number of objects" }, { "code": null, "e": 6297, "s": 6256, "text": "Operation: length, sum, mean, and cumsum" }, { "code": null, "e": 6364, "s": 6297, "text": "simplify = FALSE: Returns the output as a list instead of a vector" }, { "code": null, "e": 6403, "s": 6364, "text": "Return value: Returns a numeric value." }, { "code": null, "e": 6405, "s": 6403, "text": "R" }, { "code": "print(\"Operations using sapply() function: \") # list1 have three objects a, b, and c# and they all are numeric objects (same data type)list1 <- list(a = 11:12, b = 1:10, c = 40:60) # Printing the length of list1 objects as a listsapply(list1, length, simplify = FALSE) # Printing the sum of elements present# in the list1 objects as a listsapply(list1, sum, simplify = FALSE) # Printing the mean of elements present# in the list1 objects as a listsapply(list1, mean, simplify = FALSE) # Printing the cumulative sum of elements# present in the list1 objects as a listsapply(list1, cumsum, simplify = FALSE)", "e": 7011, "s": 6405, "text": null }, { "code": null, "e": 7019, "s": 7011, "text": "Output:" }, { "code": null, "e": 7248, "s": 7019, "text": "As we can see in the output, sapply() function returns the output as a list instead of a vector. So, we can always the third argument to the sapply() function whenever we need to print the output as a list instead of a vector. " }, { "code": null, "e": 7258, "s": 7248, "text": "ruhelaa48" }, { "code": null, "e": 7275, "s": 7258, "text": "surinderdawra388" }, { "code": null, "e": 7282, "s": 7275, "text": "Picked" }, { "code": null, "e": 7294, "s": 7282, "text": "R-Functions" }, { "code": null, "e": 7301, "s": 7294, "text": "R-List" }, { "code": null, "e": 7320, "s": 7301, "text": "Difference Between" }, { "code": null, "e": 7331, "s": 7320, "text": "R Language" }, { "code": null, "e": 7429, "s": 7331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7490, "s": 7429, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7558, "s": 7490, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 7607, "s": 7558, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 7673, "s": 7607, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 7728, "s": 7673, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 7773, "s": 7728, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 7825, "s": 7773, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 7883, "s": 7825, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 7935, "s": 7883, "text": "Change Color of Bars in Barchart using ggplot2 in R" } ]
Mid-point Formula in Coordinate Geometry
26 Oct, 2020 In geometry, a mid-point is the middle point of a line segment which is equidistant from both the endpoints. That point bisects the line into two equal halves. There are instances in Coordinate Geometry that we need to know the mid-point of two given points or mid-point of a line segment. In a cartesian plane, the midpoint of a line has its x-value as halfway between x-values of both endpoints and its y-value as halfway between y-values of both endpoints. For a line segment AB in Cartesian coordinate where the x-axis coordinate of point A is x1 and the y-axis coordinate of point A is y1 and similarly the x-axis coordinate of the point B is x2 and the y-axis coordinate of the point B is y2, the mid-point of the line will be given by (xm,ym). The formula for mid-point (xm,ym) is, Let P(x1,y1) and Q(x2,y2) be the two ends of a given line in a coordinate plane, and R(x,y) be the point on that line which divides PQ in the ratio m1:m2 such that PR/RQ = m1/m2 ...(1) Drawing lines PM, QN, and RL perpendicular on the x-axis and through R draw a straight line parallel to the x-axis to meet MP at S and NQ at T. Hence from the figure, we can say, SR = ML = OL - OM = x - x1 ...(2) RT = LN = ON - Ol = x2 - x ...(3) PS = MS - MP = LR - MP = y - y1 ...(4) TQ = NQ - NT = NQ - LR = y2 - y ...(5) Now triangle ∆SPR is similar to triangle ∆TQR, Therefore, SR/RT = PR/RQ By using equation 2, 3, and 1, we know, x - x1 / x2 - x = m1 / m2 m2x - m2x1 = m1x2 - m1x m1x + m2x = m1x2 + m2x1 (m1 + m2)x = m1x2 + m2x1 x = (m1x2 + m2x1) / (m1 + m2) Now triangle ∆SPR is similar to triangle ∆TQR, Therefore, PS/TQ = PR/RQ By using equation 4, 5, and 1, we know, y - y1 / y2 - y = m1 / m2 m2y - m2y1 = m1y2 - m1y m1y + m2y = m1y2 + m2y1 (m1 + m2)y = m1y2 + m2y1 y = (m1y2 + m2y1) / (m1 + m2) Hence the coordinates of R(x,y) are, R(x, y)= (m1x2 + m2x1) / (m1 + m2), (m1y2 + m2y1) / (m1 + m2) As we had to calculate the mid point therefore we keep the values both of m1 and m2 as same i.e. For mid-point, m1 = m2 = 1 Hence, x, y = (1.x2 + 1.x1) / (1 + 1), (1.y2 + 1.y1) / (1 + 1) x, y = (x2 + x1) / 2, (y2 + y1) / 2 Example 1: What is the mid-point of the line segment AB where point A is at (6,8) and point B is (3,1)? Solution: Let the midpoint be M(xm,ym), xm = (x1 + x2) / 2 x1 = 6, x2 = 3 xm = (6 + 3) / 2 = 9 / 2 = 4.5 ym = (y1 + y2) / 2 y1 = 8, y2 = 1 ym = (8 + 1) / 2 = 9 / 2 = 4.5 Hence the midpoint of line AB is (4.5, 4.5). Example 2: What is the mid-point of the line segment AB where point A is at (-6,4) and point B is (4,2)? Solution: Let the midpoint be M(xm,ym), x1 = -6, x2 = 4, y1 = 4, y2 = 2 (xm, ym) = ((x1 + x2) / 2, (y1 + y2) / 2) (xm, ym) = ((-6 + 4) / 2, (4 + 2) / 2) (xm, ym) = ((-2) / 2, (6) / 2) (xm, ym) = (-1, 3) Hence the midpoint of line AB is (-1, 3). Example 3: Find the value of p so that (–2, 2.5) is the midpoint between (p, 2) and (–1, 3). Solution: Let the midpoint be M(xm, ym) = (-2, 2.5) where, x1 = -1, xm = -2 y-coordinate of the end point is already known as 2, hence we need to find only the x-coordinate xm = (x1 + x2) / 2 -2 = (-1 + p) / 2 -4 = -1 + p p = -3 Hence the other end-point of the line is (-3, 2). Coordinate Geometry Picked School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Oct, 2020" }, { "code": null, "e": 514, "s": 54, "text": "In geometry, a mid-point is the middle point of a line segment which is equidistant from both the endpoints. That point bisects the line into two equal halves. There are instances in Coordinate Geometry that we need to know the mid-point of two given points or mid-point of a line segment. In a cartesian plane, the midpoint of a line has its x-value as halfway between x-values of both endpoints and its y-value as halfway between y-values of both endpoints." }, { "code": null, "e": 805, "s": 514, "text": "For a line segment AB in Cartesian coordinate where the x-axis coordinate of point A is x1 and the y-axis coordinate of point A is y1 and similarly the x-axis coordinate of the point B is x2 and the y-axis coordinate of the point B is y2, the mid-point of the line will be given by (xm,ym)." }, { "code": null, "e": 844, "s": 805, "text": "The formula for mid-point (xm,ym) is," }, { "code": null, "e": 1008, "s": 844, "text": "Let P(x1,y1) and Q(x2,y2) be the two ends of a given line in a coordinate plane, and R(x,y) be the point on that line which divides PQ in the ratio m1:m2 such that" }, { "code": null, "e": 1042, "s": 1008, "text": "PR/RQ = m1/m2 ...(1)" }, { "code": null, "e": 1186, "s": 1042, "text": "Drawing lines PM, QN, and RL perpendicular on the x-axis and through R draw a straight line parallel to the x-axis to meet MP at S and NQ at T." }, { "code": null, "e": 1221, "s": 1186, "text": "Hence from the figure, we can say," }, { "code": null, "e": 1401, "s": 1221, "text": "SR = ML = OL - OM = x - x1 ...(2)\nRT = LN = ON - Ol = x2 - x ...(3)\nPS = MS - MP = LR - MP = y - y1 ...(4)\nTQ = NQ - NT = NQ - LR = y2 - y ...(5)" }, { "code": null, "e": 1448, "s": 1401, "text": "Now triangle ∆SPR is similar to triangle ∆TQR," }, { "code": null, "e": 1459, "s": 1448, "text": "Therefore," }, { "code": null, "e": 1473, "s": 1459, "text": "SR/RT = PR/RQ" }, { "code": null, "e": 1513, "s": 1473, "text": "By using equation 2, 3, and 1, we know," }, { "code": null, "e": 1642, "s": 1513, "text": "x - x1 / x2 - x = m1 / m2\nm2x - m2x1 = m1x2 - m1x\nm1x + m2x = m1x2 + m2x1\n(m1 + m2)x = m1x2 + m2x1\nx = (m1x2 + m2x1) / (m1 + m2)" }, { "code": null, "e": 1689, "s": 1642, "text": "Now triangle ∆SPR is similar to triangle ∆TQR," }, { "code": null, "e": 1700, "s": 1689, "text": "Therefore," }, { "code": null, "e": 1714, "s": 1700, "text": "PS/TQ = PR/RQ" }, { "code": null, "e": 1754, "s": 1714, "text": "By using equation 4, 5, and 1, we know," }, { "code": null, "e": 1883, "s": 1754, "text": "y - y1 / y2 - y = m1 / m2\nm2y - m2y1 = m1y2 - m1y\nm1y + m2y = m1y2 + m2y1\n(m1 + m2)y = m1y2 + m2y1\ny = (m1y2 + m2y1) / (m1 + m2)" }, { "code": null, "e": 1920, "s": 1883, "text": "Hence the coordinates of R(x,y) are," }, { "code": null, "e": 1982, "s": 1920, "text": "R(x, y)= (m1x2 + m2x1) / (m1 + m2), (m1y2 + m2y1) / (m1 + m2)" }, { "code": null, "e": 2080, "s": 1982, "text": "As we had to calculate the mid point therefore we keep the values both of m1 and m2 as same i.e. " }, { "code": null, "e": 2096, "s": 2080, "text": "For mid-point, " }, { "code": null, "e": 2108, "s": 2096, "text": "m1 = m2 = 1" }, { "code": null, "e": 2115, "s": 2108, "text": "Hence," }, { "code": null, "e": 2171, "s": 2115, "text": "x, y = (1.x2 + 1.x1) / (1 + 1), (1.y2 + 1.y1) / (1 + 1)" }, { "code": null, "e": 2207, "s": 2171, "text": "x, y = (x2 + x1) / 2, (y2 + y1) / 2" }, { "code": null, "e": 2311, "s": 2207, "text": "Example 1: What is the mid-point of the line segment AB where point A is at (6,8) and point B is (3,1)?" }, { "code": null, "e": 2352, "s": 2311, "text": "Solution: Let the midpoint be M(xm,ym), " }, { "code": null, "e": 2405, "s": 2352, "text": " xm = (x1 + x2) / 2" }, { "code": null, "e": 2454, "s": 2405, "text": " x1 = 6, x2 = 3" }, { "code": null, "e": 2519, "s": 2454, "text": " xm = (6 + 3) / 2 = 9 / 2 = 4.5" }, { "code": null, "e": 2572, "s": 2519, "text": " ym = (y1 + y2) / 2" }, { "code": null, "e": 2621, "s": 2572, "text": " y1 = 8, y2 = 1" }, { "code": null, "e": 2686, "s": 2621, "text": " ym = (8 + 1) / 2 = 9 / 2 = 4.5" }, { "code": null, "e": 2731, "s": 2686, "text": "Hence the midpoint of line AB is (4.5, 4.5)." }, { "code": null, "e": 2836, "s": 2731, "text": "Example 2: What is the mid-point of the line segment AB where point A is at (-6,4) and point B is (4,2)?" }, { "code": null, "e": 2876, "s": 2836, "text": "Solution: Let the midpoint be M(xm,ym)," }, { "code": null, "e": 2941, "s": 2876, "text": " x1 = -6, x2 = 4, y1 = 4, y2 = 2" }, { "code": null, "e": 3016, "s": 2941, "text": " (xm, ym) = ((x1 + x2) / 2, (y1 + y2) / 2)" }, { "code": null, "e": 3088, "s": 3016, "text": " (xm, ym) = ((-6 + 4) / 2, (4 + 2) / 2)" }, { "code": null, "e": 3152, "s": 3088, "text": " (xm, ym) = ((-2) / 2, (6) / 2)" }, { "code": null, "e": 3204, "s": 3152, "text": " (xm, ym) = (-1, 3)" }, { "code": null, "e": 3246, "s": 3204, "text": "Hence the midpoint of line AB is (-1, 3)." }, { "code": null, "e": 3339, "s": 3246, "text": "Example 3: Find the value of p so that (–2, 2.5) is the midpoint between (p, 2) and (–1, 3)." }, { "code": null, "e": 3398, "s": 3339, "text": "Solution: Let the midpoint be M(xm, ym) = (-2, 2.5) where," }, { "code": null, "e": 3447, "s": 3398, "text": " x1 = -1, xm = -2" }, { "code": null, "e": 3544, "s": 3447, "text": "y-coordinate of the end point is already known as 2, hence we need to find only the x-coordinate" }, { "code": null, "e": 3595, "s": 3544, "text": " xm = (x1 + x2) / 2" }, { "code": null, "e": 3645, "s": 3595, "text": " -2 = (-1 + p) / 2" }, { "code": null, "e": 3689, "s": 3645, "text": " -4 = -1 + p" }, { "code": null, "e": 3728, "s": 3689, "text": " p = -3" }, { "code": null, "e": 3778, "s": 3728, "text": "Hence the other end-point of the line is (-3, 2)." }, { "code": null, "e": 3798, "s": 3778, "text": "Coordinate Geometry" }, { "code": null, "e": 3805, "s": 3798, "text": "Picked" }, { "code": null, "e": 3824, "s": 3805, "text": "School Mathematics" } ]
Permute the elements of an array following given order
25 May, 2022 A permutation is a rearrangement of members of a sequence into a new sequence. For example, there are 24 permutations of [a, b, c, d]. Some of them are [b, a, d, c], [d, a, b, c] and [a, d, b, c]. A permutation can be specified by an array P[] where P[i] represents the location of the element at index i in the permutation.For example, the array [3, 2, 1, 0] represents the permutation that maps the element at index 0 to index 3, the element at index 1 to index 2, the element at index 2 to index 1 and the element at index 3 to index 0.Given the array arr[] of N elements and a permutation array P[], the task is to permute the given array arr[] based on the permutation array P[].Examples: Input: arr[] = {1, 2, 3, 4}, P[] = {3, 2, 1, 0} Output: 4 3 2 1Input: arr[] = {11, 32, 3, 42}, P[] = {2, 3, 0, 1} Output: 3 42 11 32 Approach: Every permutation can be represented by a collection of independent permutations, each of which is cyclic i.e. it moves all the elements by a fixed offset wrapping around. To find and apply the cycle that indicates entry i, just keep going forward (from i to P[i]) till we get back at i. After completing the current cycle, find another cycle that has not yet been applied. To check this, subtract n from P[i] after applying it. This means that if an entry in P[i] is negative, we have performed the corresponding move.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to permute the given// array based on the given conditionsint permute(int A[], int P[], int n){ // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A[i], A[P[next]]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} // Driver codeint main(){ int A[] = { 5, 6, 7, 8 }; int P[] = { 3, 2, 1, 0 }; int n = sizeof(A) / sizeof(int); permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) cout << A[i] << " "; return 0;} // Java implementation of the approachclass GFG{ // Function to permute the given// array based on the given conditionsstatic void permute(int A[], int P[], int n){ // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A, i, P[next]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void main(String[] args){ int A[] = { 5, 6, 7, 8 }; int P[] = { 3, 2, 1, 0 }; int n = A.length; permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) System.out.print(A[i]+ " "); }} // This code is contributed by 29AjayKumar # Python 3 implementation of the approach # Function to permute the given# array based on the given conditionsdef permute(A, P, n): # For each element of P for i in range(n): next = i # Check if it is already # considered in cycle while (P[next] >= 0): # Swap the current element according # to the permutation in P t = A[i] A[i] = A[P[next]] A[P[next]] = t temp = P[next] # Subtract n from an entry in P # to make it negative which indicates # the corresponding move # has been performed P[next] -= n next = temp # Driver codeif __name__ == '__main__': A = [5, 6, 7, 8] P = [3, 2, 1, 0] n = len(A) permute(A, P, n) # Print the new array after # applying the permutation for i in range(n): print(A[i], end = " ") # This code is contributed by Surendra_Gangwar // C# implementation of the approachusing System; class GFG{ // Function to permute the given // array based on the given conditions static void permute(int []A, int []P, int n) { // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A, i, P[next]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } } } static int[] swap(int []arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main() { int []A = { 5, 6, 7, 8 }; int []P = { 3, 2, 1, 0 }; int n = A.Length; permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) Console.Write(A[i]+ " "); }} // This code is contributed by AnkitRai01 <script> // JavaScript implementation of the approach // Function to permute the given// array based on the given conditionsfunction permute(A, P, n) { // For each element of P for (let i = 0; i < n; i++) { let next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P let x = A[i]; A[i] = A[P[next]]; A[P[next]] = x; let temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} // Driver code let A = [5, 6, 7, 8];let P = [3, 2, 1, 0];let n = A.length; permute(A, P, n); // Print the new array after// applying the permutationfor (let i = 0; i < n; i++) document.write(A[i] + " "); </script> 8 7 6 5 Time Complexity: O(n)Space Complexity : O(1) SURENDRA_GANGWAR 29AjayKumar ankthon _saurabh_jaiswal jyoti369 khushboogoyal499 ankita_saini Arrays Competitive Programming Arrays 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 Chocolate Distribution Problem What is Data Structure: Types, Classifications and Applications Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 750, "s": 54, "text": "A permutation is a rearrangement of members of a sequence into a new sequence. For example, there are 24 permutations of [a, b, c, d]. Some of them are [b, a, d, c], [d, a, b, c] and [a, d, b, c]. A permutation can be specified by an array P[] where P[i] represents the location of the element at index i in the permutation.For example, the array [3, 2, 1, 0] represents the permutation that maps the element at index 0 to index 3, the element at index 1 to index 2, the element at index 2 to index 1 and the element at index 3 to index 0.Given the array arr[] of N elements and a permutation array P[], the task is to permute the given array arr[] based on the permutation array P[].Examples: " }, { "code": null, "e": 885, "s": 750, "text": "Input: arr[] = {1, 2, 3, 4}, P[] = {3, 2, 1, 0} Output: 4 3 2 1Input: arr[] = {11, 32, 3, 42}, P[] = {2, 3, 0, 1} Output: 3 42 11 32 " }, { "code": null, "e": 1467, "s": 885, "text": "Approach: Every permutation can be represented by a collection of independent permutations, each of which is cyclic i.e. it moves all the elements by a fixed offset wrapping around. To find and apply the cycle that indicates entry i, just keep going forward (from i to P[i]) till we get back at i. After completing the current cycle, find another cycle that has not yet been applied. To check this, subtract n from P[i] after applying it. This means that if an entry in P[i] is negative, we have performed the corresponding move.Below is the implementation of the above approach: " }, { "code": null, "e": 1471, "s": 1467, "text": "C++" }, { "code": null, "e": 1476, "s": 1471, "text": "Java" }, { "code": null, "e": 1484, "s": 1476, "text": "Python3" }, { "code": null, "e": 1487, "s": 1484, "text": "C#" }, { "code": null, "e": 1498, "s": 1487, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to permute the given// array based on the given conditionsint permute(int A[], int P[], int n){ // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A[i], A[P[next]]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} // Driver codeint main(){ int A[] = { 5, 6, 7, 8 }; int P[] = { 3, 2, 1, 0 }; int n = sizeof(A) / sizeof(int); permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) cout << A[i] << \" \"; return 0;}", "e": 2527, "s": 1498, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to permute the given// array based on the given conditionsstatic void permute(int A[], int P[], int n){ // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A, i, P[next]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} static int[] swap(int []arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver codepublic static void main(String[] args){ int A[] = { 5, 6, 7, 8 }; int P[] = { 3, 2, 1, 0 }; int n = A.length; permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) System.out.print(A[i]+ \" \"); }} // This code is contributed by 29AjayKumar", "e": 3710, "s": 2527, "text": null }, { "code": "# Python 3 implementation of the approach # Function to permute the given# array based on the given conditionsdef permute(A, P, n): # For each element of P for i in range(n): next = i # Check if it is already # considered in cycle while (P[next] >= 0): # Swap the current element according # to the permutation in P t = A[i] A[i] = A[P[next]] A[P[next]] = t temp = P[next] # Subtract n from an entry in P # to make it negative which indicates # the corresponding move # has been performed P[next] -= n next = temp # Driver codeif __name__ == '__main__': A = [5, 6, 7, 8] P = [3, 2, 1, 0] n = len(A) permute(A, P, n) # Print the new array after # applying the permutation for i in range(n): print(A[i], end = \" \") # This code is contributed by Surendra_Gangwar", "e": 4707, "s": 3710, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to permute the given // array based on the given conditions static void permute(int []A, int []P, int n) { // For each element of P for (int i = 0; i < n; i++) { int next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P swap(A, i, P[next]); int temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } } } static int[] swap(int []arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver code public static void Main() { int []A = { 5, 6, 7, 8 }; int []P = { 3, 2, 1, 0 }; int n = A.Length; permute(A, P, n); // Print the new array after // applying the permutation for (int i = 0; i < n; i++) Console.Write(A[i]+ \" \"); }} // This code is contributed by AnkitRai01", "e": 6097, "s": 4707, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to permute the given// array based on the given conditionsfunction permute(A, P, n) { // For each element of P for (let i = 0; i < n; i++) { let next = i; // Check if it is already // considered in cycle while (P[next] >= 0) { // Swap the current element according // to the permutation in P let x = A[i]; A[i] = A[P[next]]; A[P[next]] = x; let temp = P[next]; // Subtract n from an entry in P // to make it negative which indicates // the corresponding move // has been performed P[next] -= n; next = temp; } }} // Driver code let A = [5, 6, 7, 8];let P = [3, 2, 1, 0];let n = A.length; permute(A, P, n); // Print the new array after// applying the permutationfor (let i = 0; i < n; i++) document.write(A[i] + \" \"); </script>", "e": 7077, "s": 6097, "text": null }, { "code": null, "e": 7085, "s": 7077, "text": "8 7 6 5" }, { "code": null, "e": 7132, "s": 7087, "text": "Time Complexity: O(n)Space Complexity : O(1)" }, { "code": null, "e": 7149, "s": 7132, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 7161, "s": 7149, "text": "29AjayKumar" }, { "code": null, "e": 7169, "s": 7161, "text": "ankthon" }, { "code": null, "e": 7186, "s": 7169, "text": "_saurabh_jaiswal" }, { "code": null, "e": 7195, "s": 7186, "text": "jyoti369" }, { "code": null, "e": 7212, "s": 7195, "text": "khushboogoyal499" }, { "code": null, "e": 7225, "s": 7212, "text": "ankita_saini" }, { "code": null, "e": 7232, "s": 7225, "text": "Arrays" }, { "code": null, "e": 7256, "s": 7232, "text": "Competitive Programming" }, { "code": null, "e": 7263, "s": 7256, "text": "Arrays" }, { "code": null, "e": 7361, "s": 7263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7393, "s": 7361, "text": "Introduction to Data Structures" }, { "code": null, "e": 7418, "s": 7393, "text": "Window Sliding Technique" }, { "code": null, "e": 7465, "s": 7418, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7496, "s": 7465, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7560, "s": 7496, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7603, "s": 7560, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 7646, "s": 7603, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 7687, "s": 7646, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 7714, "s": 7687, "text": "Modulo 10^9+7 (1000000007)" } ]
C++ bitset and its application - GeeksforGeeks
04 Sep, 2018 A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is not there with vector and dynamic array) As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector. We can access each bit of bitset individually with help of array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array. Remember bitset starts its indexing backward that is for 10110, 0 are at 0th and 3rd indices whereas 1 are at 1st 2nd and 4th indices.We can construct a bitset using integer number as well as binary string via constructors which is shown in below code. The size of bitset is fixed at compile time that is, it can’t be changed at runtime.The main function defined for bitset class are operator [], count, size, set, reset and many more they are explained in below code – // C++ program to demonstrate various functionality of bitset#include <bits/stdc++.h>using namespace std; #define M 32 int main(){ // default constructor initializes with all bits 0 bitset<M> bset1; // bset2 is initialized with bits of 20 bitset<M> bset2(20); // bset3 is initialized with bits of specified binary string bitset<M> bset3(string("1100")); // cout prints exact bits representation of bitset cout << bset1 << endl; // 00000000000000000000000000000000 cout << bset2 << endl; // 00000000000000000000000000010100 cout << bset3 << endl; // 00000000000000000000000000001100 cout << endl; // declaring set8 with capacity of 8 bits bitset<8> set8; // 00000000 // setting first bit (or 6th index) set8[1] = 1; // 00000010 set8[4] = set8[1]; // 00010010 cout << set8 << endl; // count function returns number of set bits in bitset int numberof1 = set8.count(); // size function returns total number of bits in bitset // so there difference will give us number of unset(0) // bits in bitset int numberof0 = set8.size() - numberof1; cout << set8 << " has " << numberof1 << " ones and " << numberof0 << " zeros\n"; // test function return 1 if bit is set else returns 0 cout << "bool representation of " << set8 << " : "; for (int i = 0; i < set8.size(); i++) cout << set8.test(i) << " "; cout << endl; // any function returns true, if atleast 1 bit // is set if (!set8.any()) cout << "set8 has no bit set.\n"; if (!bset1.any()) cout << "bset1 has no bit set.\n"; // none function returns true, if none of the bit // is set if (!bset1.none()) cout << "bset1 has some bit set\n"; // bset.set() sets all bits cout << set8.set() << endl; // bset.set(pos, b) makes bset[pos] = b cout << set8.set(4, 0) << endl; // bset.set(pos) makes bset[pos] = 1 i.e. default // is 1 cout << set8.set(4) << endl; // reset function makes all bits 0 cout << set8.reset(2) << endl; cout << set8.reset() << endl; // flip function flips all bits i.e. 1 <-> 0 // and 0 <-> 1 cout << set8.flip(2) << endl; cout << set8.flip() << endl; // Converting decimal number to binary by using bitset int num = 100; cout << "\nDecimal number: " << num << " Binary equivalent: " << bitset<8>(num); return 0;} Output : 00000000000000000000000000000000 00000000000000000000000000010100 00000000000000000000000000001100 00010010 00010010 has 2 ones and 6 zeros bool representation of 00010010 : 0 1 0 0 1 0 0 0 bset1 has no bit set. 11111111 11101111 11111111 11111011 00000000 00000100 11111011 Decimal number: 100 Binary equivalent: 01100100 For bitset set, reset and flip function are defined. Set function sets (1) all bits of bitset if no argument is provided otherwise it sets the bit whose position is given as argument. In same way reset and flip also work if they are called with no argument they perform their operation on whole bitset and if some position is provided as argument then they perform operation at that position only.For bitset all bitwise operator are overloaded that is they can be applied to bitset directly without any casting or conversion, main overloaded operator are &, |, ==, != and shifting operator <> which makes operation on bitset easy.Use of above operator is shown in below code. // C++ program to show applicable operator on bitset.#include <bits/stdc++.h>using namespace std; int main(){ bitset<4> bset1(9); // bset1 contains 1001 bitset<4> bset2(3); // bset2 contains 0011 // comparison operator cout << (bset1 == bset2) << endl; // false 0 cout << (bset1 != bset2) << endl; // true 1 // bitwise operation and assignment cout << (bset1 ^= bset2) << endl; // 1010 cout << (bset1 &= bset2) << endl; // 0010 cout << (bset1 |= bset2) << endl; // 0011 // left and right shifting cout << (bset1 <<= 2) << endl; // 1100 cout << (bset1 >>= 1) << endl; // 0110 // not operator cout << (~bset2) << endl; // 1100 // bitwise operator cout << (bset1 & bset2) << endl; // 0010 cout << (bset1 | bset2) << endl; // 0111 cout << (bset1 ^ bset2) << endl; // 0101} Output : 0 1 1010 0010 0011 1100 0110 1100 0010 0111 0101 This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. upsurge CPP-bitset CPP-Library STL Bit Magic C Language C++ Bit Magic STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Bit Fields in C Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Arrays in C/C++ std::sort() in C++ STL Multidimensional Arrays in C / C++ rand() and srand() in C/C++
[ { "code": null, "e": 24978, "s": 24950, "text": "\n04 Sep, 2018" }, { "code": null, "e": 25359, "s": 24978, "text": "A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is not there with vector and dynamic array)" }, { "code": null, "e": 26114, "s": 25359, "text": "As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector. We can access each bit of bitset individually with help of array indexing operator [] that is bs[3] shows bit at index 3 of bitset bs just like a simple array. Remember bitset starts its indexing backward that is for 10110, 0 are at 0th and 3rd indices whereas 1 are at 1st 2nd and 4th indices.We can construct a bitset using integer number as well as binary string via constructors which is shown in below code. The size of bitset is fixed at compile time that is, it can’t be changed at runtime.The main function defined for bitset class are operator [], count, size, set, reset and many more they are explained in below code –" }, { "code": "// C++ program to demonstrate various functionality of bitset#include <bits/stdc++.h>using namespace std; #define M 32 int main(){ // default constructor initializes with all bits 0 bitset<M> bset1; // bset2 is initialized with bits of 20 bitset<M> bset2(20); // bset3 is initialized with bits of specified binary string bitset<M> bset3(string(\"1100\")); // cout prints exact bits representation of bitset cout << bset1 << endl; // 00000000000000000000000000000000 cout << bset2 << endl; // 00000000000000000000000000010100 cout << bset3 << endl; // 00000000000000000000000000001100 cout << endl; // declaring set8 with capacity of 8 bits bitset<8> set8; // 00000000 // setting first bit (or 6th index) set8[1] = 1; // 00000010 set8[4] = set8[1]; // 00010010 cout << set8 << endl; // count function returns number of set bits in bitset int numberof1 = set8.count(); // size function returns total number of bits in bitset // so there difference will give us number of unset(0) // bits in bitset int numberof0 = set8.size() - numberof1; cout << set8 << \" has \" << numberof1 << \" ones and \" << numberof0 << \" zeros\\n\"; // test function return 1 if bit is set else returns 0 cout << \"bool representation of \" << set8 << \" : \"; for (int i = 0; i < set8.size(); i++) cout << set8.test(i) << \" \"; cout << endl; // any function returns true, if atleast 1 bit // is set if (!set8.any()) cout << \"set8 has no bit set.\\n\"; if (!bset1.any()) cout << \"bset1 has no bit set.\\n\"; // none function returns true, if none of the bit // is set if (!bset1.none()) cout << \"bset1 has some bit set\\n\"; // bset.set() sets all bits cout << set8.set() << endl; // bset.set(pos, b) makes bset[pos] = b cout << set8.set(4, 0) << endl; // bset.set(pos) makes bset[pos] = 1 i.e. default // is 1 cout << set8.set(4) << endl; // reset function makes all bits 0 cout << set8.reset(2) << endl; cout << set8.reset() << endl; // flip function flips all bits i.e. 1 <-> 0 // and 0 <-> 1 cout << set8.flip(2) << endl; cout << set8.flip() << endl; // Converting decimal number to binary by using bitset int num = 100; cout << \"\\nDecimal number: \" << num << \" Binary equivalent: \" << bitset<8>(num); return 0;}", "e": 28537, "s": 26114, "text": null }, { "code": null, "e": 28546, "s": 28537, "text": "Output :" }, { "code": null, "e": 28873, "s": 28546, "text": "00000000000000000000000000000000\n00000000000000000000000000010100\n00000000000000000000000000001100\n\n00010010\n00010010 has 2 ones and 6 zeros\nbool representation of 00010010 : 0 1 0 0 1 0 0 0 \nbset1 has no bit set.\n11111111\n11101111\n11111111\n11111011\n00000000\n00000100\n11111011\n\nDecimal number: 100 Binary equivalent: 01100100\n" }, { "code": null, "e": 29549, "s": 28873, "text": "For bitset set, reset and flip function are defined. Set function sets (1) all bits of bitset if no argument is provided otherwise it sets the bit whose position is given as argument. In same way reset and flip also work if they are called with no argument they perform their operation on whole bitset and if some position is provided as argument then they perform operation at that position only.For bitset all bitwise operator are overloaded that is they can be applied to bitset directly without any casting or conversion, main overloaded operator are &, |, ==, != and shifting operator <> which makes operation on bitset easy.Use of above operator is shown in below code." }, { "code": "// C++ program to show applicable operator on bitset.#include <bits/stdc++.h>using namespace std; int main(){ bitset<4> bset1(9); // bset1 contains 1001 bitset<4> bset2(3); // bset2 contains 0011 // comparison operator cout << (bset1 == bset2) << endl; // false 0 cout << (bset1 != bset2) << endl; // true 1 // bitwise operation and assignment cout << (bset1 ^= bset2) << endl; // 1010 cout << (bset1 &= bset2) << endl; // 0010 cout << (bset1 |= bset2) << endl; // 0011 // left and right shifting cout << (bset1 <<= 2) << endl; // 1100 cout << (bset1 >>= 1) << endl; // 0110 // not operator cout << (~bset2) << endl; // 1100 // bitwise operator cout << (bset1 & bset2) << endl; // 0010 cout << (bset1 | bset2) << endl; // 0111 cout << (bset1 ^ bset2) << endl; // 0101}", "e": 30384, "s": 29549, "text": null }, { "code": null, "e": 30393, "s": 30384, "text": "Output :" }, { "code": null, "e": 30443, "s": 30393, "text": "0\n1\n1010\n0010\n0011\n1100\n0110\n1100\n0010\n0111\n0101\n" }, { "code": null, "e": 30616, "s": 30443, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30624, "s": 30616, "text": "upsurge" }, { "code": null, "e": 30635, "s": 30624, "text": "CPP-bitset" }, { "code": null, "e": 30647, "s": 30635, "text": "CPP-Library" }, { "code": null, "e": 30651, "s": 30647, "text": "STL" }, { "code": null, "e": 30661, "s": 30651, "text": "Bit Magic" }, { "code": null, "e": 30672, "s": 30661, "text": "C Language" }, { "code": null, "e": 30676, "s": 30672, "text": "C++" }, { "code": null, "e": 30686, "s": 30676, "text": "Bit Magic" }, { "code": null, "e": 30690, "s": 30686, "text": "STL" }, { "code": null, "e": 30694, "s": 30690, "text": "CPP" }, { "code": null, "e": 30792, "s": 30694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30838, "s": 30792, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30868, "s": 30838, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 30921, "s": 30868, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 30961, "s": 30921, "text": "Binary representation of a given number" }, { "code": null, "e": 30977, "s": 30961, "text": "Bit Fields in C" }, { "code": null, "e": 31055, "s": 30977, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 31071, "s": 31055, "text": "Arrays in C/C++" }, { "code": null, "e": 31094, "s": 31071, "text": "std::sort() in C++ STL" }, { "code": null, "e": 31129, "s": 31094, "text": "Multidimensional Arrays in C / C++" } ]
Count of distinct Numbers that can be formed by chess knight in N moves on a mobile keypad - GeeksforGeeks
11 Feb, 2022 Given an integer N and a chess knight placed in mobile keypad. The task is to count the total distinct N digit numbers which can be formed by the chess knight with N moves. As the answer can be very large give the value of answer modulo 109 + 7. Note: In each move a chess knight can move 2 units horizontally and one unit vertically or two units vertically and one unit horizontally. A demo mobile keypad is shown in image where ‘*’ and ‘#’ are not considered as part of a number. Examples: Input: N = 1Output: 10Explanation: Placing the knight over any numeric cell of the 10 cells is sufficient. Input: N = 2Output: 20Explanation: All the valid number are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94] Approach: The idea is to find the possible cells that can be reached from a given cell for every cell and add all of them to find the answer. Follow the steps below to solve the problem: Initialize the vector v[10, 1], and temp[10]. Iterate over the range [1, N) using the variable i and perform the following tasks:Find the values for all cells in temp[] and then store them in vector v[]. Find the values for all cells in temp[] and then store them in vector v[]. Initialize the variable sum as 0 to store the answer. Iterate over the range [0, 10) using the variable i and perform the following tasks:Add the value of v[i] to the variable sum. Add the value of v[i] to the variable sum. After performing the above steps, print the value of sum as the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total number of waysint knightCalling(int N){ int mod = 1000000007; // Base Case if (N == 1) return 10; vector<int> v(10, 1); vector<int> temp(10); // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[j] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum;} // Driver Codeint main(){ int N = 2; cout << knightCalling(N);} // This code is contributed by Samim Hossain Mondal. // Java program for the above approachimport java.util.*;class GFG{ // Function to find the total number of waysstatic int knightCalling(int N){ int mod = 1000000007; // Base Case if (N == 1) return 10; int []v = new int[10]; int []temp = new int[10]; Arrays.fill(v, 1); // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[i] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum;} // Driver Codepublic static void main(String[] args){ int N = 2; System.out.print(knightCalling(N));}} // This code is contributed by 29AjayKumar # Python 3 program for the above approach # Function to find the total number of waysdef knightCalling(N): mod = 1000000007 # Base Case if (N == 1): return 10 v = [1]*10 temp = [0]*10 # No cell can be reached from a # cell with value 5 v[5] = 0 for i in range(1, N): # Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod temp[1] = (v[6] + v[8]) % mod temp[2] = (v[7] + v[9]) % mod temp[3] = (v[4] + v[8]) % mod temp[4] = (v[0] + v[3] + v[9]) % mod temp[6] = (v[0] + v[1] + v[7]) % mod temp[7] = (v[2] + v[6]) % mod temp[8] = (v[1] + v[3]) % mod temp[9] = (v[2] + v[4]) % mod # Store them for j in range(10): v[j] = temp[j] # Find the answer sum = 0 for i in range(10): sum = (sum + v[i]) % mod return sum # Driver Codeif __name__ == "__main__": N = 2 print(knightCalling(N)) # This code is contributed by ukasp. // C# program for the above approachusing System;class GFG{ // Function to find the total number of ways static int knightCalling(int N) { int mod = 1000000007; // Base Case if (N == 1) return 10; int []v = new int[10]; int []temp = new int[10]; for(int i = 0; i < 10; i++) { v[i] = 1; } // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[j] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum; } // Driver Code public static void Main() { int N = 2; Console.Write(knightCalling(N)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find the total number of ways function knightCalling(N) { let mod = 1000000007; // Base Case if (N == 1) return 10; let v = new Array(10).fill(1) let temp = new Array(10).fill(0); // No cell can be reached from a // cell with value 5 v[5] = 0; for (let i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (let i = 0; i < 10; i++) v[i] = temp[i]; } // Find the answer let sum = 0; for (let i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum; } // Driver Code let N = 2; document.write(knightCalling(N)); // This code is contributed by Potta Lokesh </script> 20 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 29AjayKumar samim2000 ukasp Algo-Geek 2021 chessboard-problems Permutation and Combination Algo Geek Arrays Mathematical Recursion Arrays Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of operation required to water all the plants Check if the given string is valid English word or not Sort strings on the basis of their numeric part Encode given String by inserting in Matrix column-wise and printing it row-wise Lexicographically smallest string formed by concatenating any prefix and its mirrored form Arrays in Java Maximum and minimum of an array using minimum number of comparisons Arrays in C/C++ Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26168, "s": 26140, "text": "\n11 Feb, 2022" }, { "code": null, "e": 26414, "s": 26168, "text": "Given an integer N and a chess knight placed in mobile keypad. The task is to count the total distinct N digit numbers which can be formed by the chess knight with N moves. As the answer can be very large give the value of answer modulo 109 + 7." }, { "code": null, "e": 26553, "s": 26414, "text": "Note: In each move a chess knight can move 2 units horizontally and one unit vertically or two units vertically and one unit horizontally." }, { "code": null, "e": 26650, "s": 26553, "text": "A demo mobile keypad is shown in image where ‘*’ and ‘#’ are not considered as part of a number." }, { "code": null, "e": 26660, "s": 26650, "text": "Examples:" }, { "code": null, "e": 26767, "s": 26660, "text": "Input: N = 1Output: 10Explanation: Placing the knight over any numeric cell of the 10 cells is sufficient." }, { "code": null, "e": 26908, "s": 26767, "text": "Input: N = 2Output: 20Explanation: All the valid number are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]" }, { "code": null, "e": 27095, "s": 26908, "text": "Approach: The idea is to find the possible cells that can be reached from a given cell for every cell and add all of them to find the answer. Follow the steps below to solve the problem:" }, { "code": null, "e": 27141, "s": 27095, "text": "Initialize the vector v[10, 1], and temp[10]." }, { "code": null, "e": 27299, "s": 27141, "text": "Iterate over the range [1, N) using the variable i and perform the following tasks:Find the values for all cells in temp[] and then store them in vector v[]." }, { "code": null, "e": 27374, "s": 27299, "text": "Find the values for all cells in temp[] and then store them in vector v[]." }, { "code": null, "e": 27428, "s": 27374, "text": "Initialize the variable sum as 0 to store the answer." }, { "code": null, "e": 27555, "s": 27428, "text": "Iterate over the range [0, 10) using the variable i and perform the following tasks:Add the value of v[i] to the variable sum." }, { "code": null, "e": 27598, "s": 27555, "text": "Add the value of v[i] to the variable sum." }, { "code": null, "e": 27670, "s": 27598, "text": "After performing the above steps, print the value of sum as the answer." }, { "code": null, "e": 27721, "s": 27670, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27725, "s": 27721, "text": "C++" }, { "code": null, "e": 27730, "s": 27725, "text": "Java" }, { "code": null, "e": 27738, "s": 27730, "text": "Python3" }, { "code": null, "e": 27741, "s": 27738, "text": "C#" }, { "code": null, "e": 27752, "s": 27741, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total number of waysint knightCalling(int N){ int mod = 1000000007; // Base Case if (N == 1) return 10; vector<int> v(10, 1); vector<int> temp(10); // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[j] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum;} // Driver Codeint main(){ int N = 2; cout << knightCalling(N);} // This code is contributed by Samim Hossain Mondal.", "e": 28885, "s": 27752, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the total number of waysstatic int knightCalling(int N){ int mod = 1000000007; // Base Case if (N == 1) return 10; int []v = new int[10]; int []temp = new int[10]; Arrays.fill(v, 1); // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[i] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum;} // Driver Codepublic static void main(String[] args){ int N = 2; System.out.print(knightCalling(N));}} // This code is contributed by 29AjayKumar", "e": 30067, "s": 28885, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the total number of waysdef knightCalling(N): mod = 1000000007 # Base Case if (N == 1): return 10 v = [1]*10 temp = [0]*10 # No cell can be reached from a # cell with value 5 v[5] = 0 for i in range(1, N): # Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod temp[1] = (v[6] + v[8]) % mod temp[2] = (v[7] + v[9]) % mod temp[3] = (v[4] + v[8]) % mod temp[4] = (v[0] + v[3] + v[9]) % mod temp[6] = (v[0] + v[1] + v[7]) % mod temp[7] = (v[2] + v[6]) % mod temp[8] = (v[1] + v[3]) % mod temp[9] = (v[2] + v[4]) % mod # Store them for j in range(10): v[j] = temp[j] # Find the answer sum = 0 for i in range(10): sum = (sum + v[i]) % mod return sum # Driver Codeif __name__ == \"__main__\": N = 2 print(knightCalling(N)) # This code is contributed by ukasp.", "e": 31069, "s": 30067, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the total number of ways static int knightCalling(int N) { int mod = 1000000007; // Base Case if (N == 1) return 10; int []v = new int[10]; int []temp = new int[10]; for(int i = 0; i < 10; i++) { v[i] = 1; } // No cell can be reached from a // cell with value 5 v[5] = 0; for (int i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (int j = 0; j < 10; j++) v[j] = temp[i]; } // Find the answer int sum = 0; for (int i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum; } // Driver Code public static void Main() { int N = 2; Console.Write(knightCalling(N)); }} // This code is contributed by Samim Hossain Mondal.", "e": 32246, "s": 31069, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the total number of ways function knightCalling(N) { let mod = 1000000007; // Base Case if (N == 1) return 10; let v = new Array(10).fill(1) let temp = new Array(10).fill(0); // No cell can be reached from a // cell with value 5 v[5] = 0; for (let i = 1; i < N; i++) { // Find the possible values from all cells temp[0] = (v[4] + v[6]) % mod; temp[1] = (v[6] + v[8]) % mod; temp[2] = (v[7] + v[9]) % mod; temp[3] = (v[4] + v[8]) % mod; temp[4] = (v[0] + v[3] + v[9]) % mod; temp[6] = (v[0] + v[1] + v[7]) % mod; temp[7] = (v[2] + v[6]) % mod; temp[8] = (v[1] + v[3]) % mod; temp[9] = (v[2] + v[4]) % mod; // Store them for (let i = 0; i < 10; i++) v[i] = temp[i]; } // Find the answer let sum = 0; for (let i = 0; i < 10; i++) sum = (sum + v[i]) % mod; return sum; } // Driver Code let N = 2; document.write(knightCalling(N)); // This code is contributed by Potta Lokesh </script>", "e": 33625, "s": 32246, "text": null }, { "code": null, "e": 33631, "s": 33628, "text": "20" }, { "code": null, "e": 33676, "s": 33633, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 33692, "s": 33678, "text": "lokeshpotta20" }, { "code": null, "e": 33704, "s": 33692, "text": "29AjayKumar" }, { "code": null, "e": 33714, "s": 33704, "text": "samim2000" }, { "code": null, "e": 33720, "s": 33714, "text": "ukasp" }, { "code": null, "e": 33735, "s": 33720, "text": "Algo-Geek 2021" }, { "code": null, "e": 33755, "s": 33735, "text": "chessboard-problems" }, { "code": null, "e": 33783, "s": 33755, "text": "Permutation and Combination" }, { "code": null, "e": 33793, "s": 33783, "text": "Algo Geek" }, { "code": null, "e": 33800, "s": 33793, "text": "Arrays" }, { "code": null, "e": 33813, "s": 33800, "text": "Mathematical" }, { "code": null, "e": 33823, "s": 33813, "text": "Recursion" }, { "code": null, "e": 33830, "s": 33823, "text": "Arrays" }, { "code": null, "e": 33843, "s": 33830, "text": "Mathematical" }, { "code": null, "e": 33853, "s": 33843, "text": "Recursion" }, { "code": null, "e": 33951, "s": 33853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34003, "s": 33951, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 34058, "s": 34003, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 34106, "s": 34058, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 34186, "s": 34106, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 34277, "s": 34186, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 34292, "s": 34277, "text": "Arrays in Java" }, { "code": null, "e": 34360, "s": 34292, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34376, "s": 34360, "text": "Arrays in C/C++" }, { "code": null, "e": 34422, "s": 34376, "text": "Write a program to reverse an array or string" } ]
Python vs. Goats: Monty Hall revisited | by Norbert Widmann | Towards Data Science
The photo of playing Pandas notwithstanding, we going to talk about the Monty Hall problem here. This problem is famous in statistics and probably has introduced the majority of statistics courses in university, online or anywhere. What most people including me learn from this problem is that statistical or probabilistic thinking is unfortunately counterintuitive and therefore has to be trained. Or in other words: Just learning the formulas will not get you all that far beyond passing the course. But now back to the actual problem: You are the lucky person who participates in a game show. The main price is an expensive sports car, probably battery electric nowadays. Between you and driving away in a brand new car are three doors. Behind two of the doors are goats and behind one door the car of your dreams. How can you defeat the goats and get the car? The rules of the game are: You choose a door. Then Monty, the talk show host, chooses another door, opens it and behind it is invariably a goat. So one of the goats is already out of the way. Now what do you do? Change to the second closed door or stick with the lucky feeling that made you choose your door. My first intuition said it does not matter: three doors, one car makes a one third chance. Monty’s action does not matter, he always chooses a goat. Or does it? Now mathematics says it does, especially taking into account the work of some Thomas Bayes. I read quite a few explanations of the problem, also on Medium. None of them struck as me as immediately understandable. So why not just try it out? Being out of an unlimited amount of goats and sports cars I chose to simulate using Python with some help from Pandas. The problem can easily be broken down into the following steps: We hide a car behind one of the three doors and two goats behind the other two.We choose a door, due to lack of further information at random, just following our lucky feeling.Monty, the friendly quiz show host, choose one of the other two doors, opens it and invariably a goat walks out of it.He offers us to change doors. What do we do?Our door is opened. We either drive into the sunset in a brand new car or have to accomodate a new pet. We hide a car behind one of the three doors and two goats behind the other two. We choose a door, due to lack of further information at random, just following our lucky feeling. Monty, the friendly quiz show host, choose one of the other two doors, opens it and invariably a goat walks out of it. He offers us to change doors. What do we do? Our door is opened. We either drive into the sunset in a brand new car or have to accomodate a new pet. There is only one decision point in step 4. We will aid our Python in this step by defining three scenarios and simulating all three of them: Scenario A: Always change. Scenario N: Never change, stick with that lucky feeling. Scenario S: Sometimes change, due to lack of better understanding of the problem with a 50:50 chance between the two unopened doors. In which scenario can we defeat the goats? Clearly, we are talking about probabilities here. So unfortunately neither mathematics nor Python can help the lucky quiz show guest in always getting the sports car. But Python can help us in getting the probabilities and actually believing them. Something where mathematics at least for me always had its difficulties getting me. I will explain a bit about the code here. The goal was to make the code as readable and understandable as possible and sacrifice efficiency both in memory and performance for it. So you will be able to find much more concise and efficient simulations of the problem. We start by modelling the Monty Hall problem using a Pandas dataframe. Note the number_games is an integer defining the number of games we want to play. all_games = pd.DataFrame(index=range(0, number_games), columns=['Door_A', 'Door_B', 'Door_C', 'Choice_1', 'Choice_Monty', 'Choice_A', 'Choice_N', 'Choice_S', 'Success_A', 'Success_N', 'Success_S'])for game_idx in all_games.index: # we put goats behind all doors all_games.loc[game_idx, ["Door_A", "Door_B", "Door_C"]] = ["Goat", "Goat", "Goat"] # oops, we forgot the car all_games.loc[game_idx, random.choice(["Door_A", "Door_B", "Door_C"])] = "Car" # the first choice is purely random all_games.loc[game_idx, "Choice_1"] = random.choice(["Door_A", "Door_B", "Door_C"]) If you take a look at the generated Pandas dataframe you will see that for all the games we hid a car behind one of the Doors A to C and two Goats behind the other two. We already picked a door. The next step is Monty’s choice and this is where the magic happens. His choice is far from random. for game_idx in all_games.index: game = all_games.iloc[game_idx] # Monty will not open the door we chose monty_choices = {"Door_A", "Door_B", "Door_C"} - {game["Choice_1"]} monty_choices = list(monty_choices) # Monty will not open the door with the car if(game[monty_choices[0]] == "Car"): monty_choice = monty_choices[1] elif(game[monty_choices[1]] == "Car"): monty_choice = monty_choices[0] else: monty_choice = random.choice(monty_choices) # We store Monty's choice all_games.loc[game_idx, "Choice_Monty"] = monty_choice After Monty made his choice we apply our three strategies as defined above: A for always change, N for never change and S for sometimes change with a 50:50 probability. # never changeall_games["Choice_N"] = all_games["Choice_1"]for game_idx in all_games.index: game = all_games.iloc[game_idx] # always change all_games["Choice_A"][game_idx] = ({"Door_A", "Door_B", "Door_C"} - {game["Choice_1"], game["Choice_Monty"]}).pop() # sometimes change all_games["Choice_S"][game_idx] = random.choice(list({"Door_A", "Door_B", "Door_C"} - {game["Choice_Monty"]})) The code should be readable even if you are not a Python aficionado. In the always change case we need the pop() to get the only remaining element from the set. The last step is scoring our scenarios with 1 if we actually got the car and 0 if we are left with a somewhat smelly four legged addition to our household. I will leave that to the reader, alternatively you can get the source code on my GitHub. Once we have scored the simulation we can simply use describe() on our dataframe to get the results. In one of my runs of 10,000 games I got the folowing values: Scenario A: 0.6659 probability of getting the car if we always change. Scenario N: 0.3341 probability if we never change, Scenario S: 0.4980 probability if we sometimes change. Looking at the results of our code we can see that the scenario A of always switching doors leaves us with a two thirds probability of getting the sports car. So in the long run 2 out of 3 times we will get the car instead of a useless goat. Why is that so? Following scenario N to never change we stick with the situation of three doors, no previous information, the chance of one third. But Monty shows us one door with a goat. So he transfers the problem into a two-door 50:50 chance problem of getting the car. This is reflected in the scenario S to sometimes change doors. But there is a third alternative reflected in scenario A to always change. With our choice, we partition the doors into two sets: Our door with a one third chance of holding the car and the other two doors with a two thirds chance. So our choice adds information by doing exactly this partitioning. Now Monty looks only at the two door partition with the two thirds chance. After Monty’s choice we can be sure that the unopened door in that partition hides the car if it was there in the first place. So we inherit the two thirds probability by always choosing that door. Still difficult to understand? Well, yes, I agree. But just look at the numbers the simulation gave us. Simulating in Python helped me in defeating the goats and get a better understanding of the problem. Hopefully, it will do the same for you! Just get the code and try for yourself for example 10,000 times. This will give you a reasonably exact estimate of the probabilities. How exact? I have to go back to my statistics courses for that one.
[ { "code": null, "e": 549, "s": 47, "text": "The photo of playing Pandas notwithstanding, we going to talk about the Monty Hall problem here. This problem is famous in statistics and probably has introduced the majority of statistics courses in university, online or anywhere. What most people including me learn from this problem is that statistical or probabilistic thinking is unfortunately counterintuitive and therefore has to be trained. Or in other words: Just learning the formulas will not get you all that far beyond passing the course." }, { "code": null, "e": 911, "s": 549, "text": "But now back to the actual problem: You are the lucky person who participates in a game show. The main price is an expensive sports car, probably battery electric nowadays. Between you and driving away in a brand new car are three doors. Behind two of the doors are goats and behind one door the car of your dreams. How can you defeat the goats and get the car?" }, { "code": null, "e": 1381, "s": 911, "text": "The rules of the game are: You choose a door. Then Monty, the talk show host, chooses another door, opens it and behind it is invariably a goat. So one of the goats is already out of the way. Now what do you do? Change to the second closed door or stick with the lucky feeling that made you choose your door. My first intuition said it does not matter: three doors, one car makes a one third chance. Monty’s action does not matter, he always chooses a goat. Or does it?" }, { "code": null, "e": 1741, "s": 1381, "text": "Now mathematics says it does, especially taking into account the work of some Thomas Bayes. I read quite a few explanations of the problem, also on Medium. None of them struck as me as immediately understandable. So why not just try it out? Being out of an unlimited amount of goats and sports cars I chose to simulate using Python with some help from Pandas." }, { "code": null, "e": 1805, "s": 1741, "text": "The problem can easily be broken down into the following steps:" }, { "code": null, "e": 2247, "s": 1805, "text": "We hide a car behind one of the three doors and two goats behind the other two.We choose a door, due to lack of further information at random, just following our lucky feeling.Monty, the friendly quiz show host, choose one of the other two doors, opens it and invariably a goat walks out of it.He offers us to change doors. What do we do?Our door is opened. We either drive into the sunset in a brand new car or have to accomodate a new pet." }, { "code": null, "e": 2327, "s": 2247, "text": "We hide a car behind one of the three doors and two goats behind the other two." }, { "code": null, "e": 2425, "s": 2327, "text": "We choose a door, due to lack of further information at random, just following our lucky feeling." }, { "code": null, "e": 2544, "s": 2425, "text": "Monty, the friendly quiz show host, choose one of the other two doors, opens it and invariably a goat walks out of it." }, { "code": null, "e": 2589, "s": 2544, "text": "He offers us to change doors. What do we do?" }, { "code": null, "e": 2693, "s": 2589, "text": "Our door is opened. We either drive into the sunset in a brand new car or have to accomodate a new pet." }, { "code": null, "e": 2835, "s": 2693, "text": "There is only one decision point in step 4. We will aid our Python in this step by defining three scenarios and simulating all three of them:" }, { "code": null, "e": 2862, "s": 2835, "text": "Scenario A: Always change." }, { "code": null, "e": 2919, "s": 2862, "text": "Scenario N: Never change, stick with that lucky feeling." }, { "code": null, "e": 3052, "s": 2919, "text": "Scenario S: Sometimes change, due to lack of better understanding of the problem with a 50:50 chance between the two unopened doors." }, { "code": null, "e": 3095, "s": 3052, "text": "In which scenario can we defeat the goats?" }, { "code": null, "e": 3469, "s": 3095, "text": "Clearly, we are talking about probabilities here. So unfortunately neither mathematics nor Python can help the lucky quiz show guest in always getting the sports car. But Python can help us in getting the probabilities and actually believing them. Something where mathematics at least for me always had its difficulties getting me. I will explain a bit about the code here." }, { "code": null, "e": 3847, "s": 3469, "text": "The goal was to make the code as readable and understandable as possible and sacrifice efficiency both in memory and performance for it. So you will be able to find much more concise and efficient simulations of the problem. We start by modelling the Monty Hall problem using a Pandas dataframe. Note the number_games is an integer defining the number of games we want to play." }, { "code": null, "e": 4570, "s": 3847, "text": "all_games = pd.DataFrame(index=range(0, number_games), columns=['Door_A', 'Door_B', 'Door_C', 'Choice_1', 'Choice_Monty', 'Choice_A', 'Choice_N', 'Choice_S', 'Success_A', 'Success_N', 'Success_S'])for game_idx in all_games.index: # we put goats behind all doors all_games.loc[game_idx, [\"Door_A\", \"Door_B\", \"Door_C\"]] = [\"Goat\", \"Goat\", \"Goat\"] # oops, we forgot the car all_games.loc[game_idx, random.choice([\"Door_A\", \"Door_B\", \"Door_C\"])] = \"Car\" # the first choice is purely random all_games.loc[game_idx, \"Choice_1\"] = random.choice([\"Door_A\", \"Door_B\", \"Door_C\"])" }, { "code": null, "e": 4865, "s": 4570, "text": "If you take a look at the generated Pandas dataframe you will see that for all the games we hid a car behind one of the Doors A to C and two Goats behind the other two. We already picked a door. The next step is Monty’s choice and this is where the magic happens. His choice is far from random." }, { "code": null, "e": 5440, "s": 4865, "text": "for game_idx in all_games.index: game = all_games.iloc[game_idx] # Monty will not open the door we chose monty_choices = {\"Door_A\", \"Door_B\", \"Door_C\"} - {game[\"Choice_1\"]} monty_choices = list(monty_choices) # Monty will not open the door with the car if(game[monty_choices[0]] == \"Car\"): monty_choice = monty_choices[1] elif(game[monty_choices[1]] == \"Car\"): monty_choice = monty_choices[0] else: monty_choice = random.choice(monty_choices) # We store Monty's choice all_games.loc[game_idx, \"Choice_Monty\"] = monty_choice" }, { "code": null, "e": 5609, "s": 5440, "text": "After Monty made his choice we apply our three strategies as defined above: A for always change, N for never change and S for sometimes change with a 50:50 probability." }, { "code": null, "e": 6010, "s": 5609, "text": "# never changeall_games[\"Choice_N\"] = all_games[\"Choice_1\"]for game_idx in all_games.index: game = all_games.iloc[game_idx] # always change all_games[\"Choice_A\"][game_idx] = ({\"Door_A\", \"Door_B\", \"Door_C\"} - {game[\"Choice_1\"], game[\"Choice_Monty\"]}).pop() # sometimes change all_games[\"Choice_S\"][game_idx] = random.choice(list({\"Door_A\", \"Door_B\", \"Door_C\"} - {game[\"Choice_Monty\"]}))" }, { "code": null, "e": 6416, "s": 6010, "text": "The code should be readable even if you are not a Python aficionado. In the always change case we need the pop() to get the only remaining element from the set. The last step is scoring our scenarios with 1 if we actually got the car and 0 if we are left with a somewhat smelly four legged addition to our household. I will leave that to the reader, alternatively you can get the source code on my GitHub." }, { "code": null, "e": 6578, "s": 6416, "text": "Once we have scored the simulation we can simply use describe() on our dataframe to get the results. In one of my runs of 10,000 games I got the folowing values:" }, { "code": null, "e": 6649, "s": 6578, "text": "Scenario A: 0.6659 probability of getting the car if we always change." }, { "code": null, "e": 6700, "s": 6649, "text": "Scenario N: 0.3341 probability if we never change," }, { "code": null, "e": 6755, "s": 6700, "text": "Scenario S: 0.4980 probability if we sometimes change." }, { "code": null, "e": 7013, "s": 6755, "text": "Looking at the results of our code we can see that the scenario A of always switching doors leaves us with a two thirds probability of getting the sports car. So in the long run 2 out of 3 times we will get the car instead of a useless goat. Why is that so?" }, { "code": null, "e": 7333, "s": 7013, "text": "Following scenario N to never change we stick with the situation of three doors, no previous information, the chance of one third. But Monty shows us one door with a goat. So he transfers the problem into a two-door 50:50 chance problem of getting the car. This is reflected in the scenario S to sometimes change doors." }, { "code": null, "e": 7632, "s": 7333, "text": "But there is a third alternative reflected in scenario A to always change. With our choice, we partition the doors into two sets: Our door with a one third chance of holding the car and the other two doors with a two thirds chance. So our choice adds information by doing exactly this partitioning." }, { "code": null, "e": 7905, "s": 7632, "text": "Now Monty looks only at the two door partition with the two thirds chance. After Monty’s choice we can be sure that the unopened door in that partition hides the car if it was there in the first place. So we inherit the two thirds probability by always choosing that door." } ]
MySQL query to find a match and fetch records
To find a match from records, use MySQL IN(). Let us first create a table − mysql> create table DemoTable ( Id int, FirstName varchar(20), Gender ENUM('Male','Female') ); Query OK, 0 rows affected (1.73 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(1,'Chris','Male'); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable values(10,'Emma','Female'); Query OK, 1 row affected (1.88 sec) mysql> insert into DemoTable values(9,'Emma','Male'); Query OK, 1 row affected (0.70 sec) mysql> insert into DemoTable values(11,'Isabella','Female'); Query OK, 1 row affected (0.46 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +------+-----------+--------+ | Id | FirstName | Gender | +------+-----------+--------+ | 1 | Chris | Male | | 10 | Emma | Female | | 9 | Emma | Male | | 11 | Isabella | Female | +------+-----------+--------+ 4 rows in set (0.00 sec) Following is the query to find match and fetch records with Id 1 and 11 − mysql> select *from DemoTable where Id IN(1,11); This will produce the following output − +------+-----------+--------+ | Id | FirstName | Gender | +------+-----------+--------+ | 1 | Chris | Male | | 11 | Isabella | Female | +------+-----------+--------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1138, "s": 1062, "text": "To find a match from records, use MySQL IN(). Let us first create a table −" }, { "code": null, "e": 1279, "s": 1138, "text": "mysql> create table DemoTable\n(\n Id int,\n FirstName varchar(20),\n Gender ENUM('Male','Female')\n);\nQuery OK, 0 rows affected (1.73 sec)" }, { "code": null, "e": 1335, "s": 1279, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1706, "s": 1335, "text": "mysql> insert into DemoTable values(1,'Chris','Male');\nQuery OK, 1 row affected (0.47 sec)\nmysql> insert into DemoTable values(10,'Emma','Female');\nQuery OK, 1 row affected (1.88 sec)\nmysql> insert into DemoTable values(9,'Emma','Male');\nQuery OK, 1 row affected (0.70 sec)\nmysql> insert into DemoTable values(11,'Isabella','Female');\nQuery OK, 1 row affected (0.46 sec)" }, { "code": null, "e": 1766, "s": 1706, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1797, "s": 1766, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1838, "s": 1797, "text": "This will produce the following output −" }, { "code": null, "e": 2103, "s": 1838, "text": "+------+-----------+--------+\n| Id | FirstName | Gender |\n+------+-----------+--------+\n| 1 | Chris | Male |\n| 10 | Emma | Female |\n| 9 | Emma | Male |\n| 11 | Isabella | Female |\n+------+-----------+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2177, "s": 2103, "text": "Following is the query to find match and fetch records with Id 1 and 11 −" }, { "code": null, "e": 2226, "s": 2177, "text": "mysql> select *from DemoTable where Id IN(1,11);" }, { "code": null, "e": 2267, "s": 2226, "text": "This will produce the following output −" }, { "code": null, "e": 2472, "s": 2267, "text": "+------+-----------+--------+\n| Id | FirstName | Gender |\n+------+-----------+--------+\n| 1 | Chris | Male |\n| 11 | Isabella | Female |\n+------+-----------+--------+\n2 rows in set (0.00 sec)" } ]
Conversion Functions in Pandas DataFrame - GeeksforGeeks
25 Jul, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. In this article, we are using “nba.csv” file to download the CSV, click here. DataFrame.astype() function is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type. Code #1: Convert the Weight column data type. # importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of # the data frame for visualization df[:10] As the data have some “nan” values so, to avoid any error we will drop all the rows containing any nan values. # drop all those rows which # have any 'nan' value in it.df.dropna(inplace = True) # let's find out the data type of Weight columnbefore = type(df.Weight[0]) # Now we will convert it into 'int64' type.df.Weight = df.We<strong>ight.astype('int64') # let's find out the data type after castingafter = type(df.Weight[0]) # print the value of beforebefore # print the value of afterafter Output: # print the data frame and see# what it looks like after the changedf DataFrame.infer_objects() function attempts to infer better data type for input object column. This function attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction. Code #1: Use infer_objects() function to infer better data type. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":["sofia", 5, 8, 11, 100], "B":[2, 8, 77, 4, 11], "C":["amy", 11, 4, 6, 9]}) # Print the dataframeprint(df) Output : Let’s see the dtype (data type) of each column in the dataframe. # to print the basic infodf.info() As we can see in the output, first and third column is of object type. whereas the second column is of int64 type. Now slice the dataframe and create a new dataframe from it. # slice from the 1st row till enddf_new = df[1:] # Let's print the new data framedf_new # Now let's print the data type of the columnsdf_new.info() Output : As we can see in the output, column “A” and “C” are of object type even though they contain integer value. So, let’s try the infer_objects() function. # applying infer_objects() function.df_new = df_new.infer_objects() # Print the dtype after applying the functiondf_new.info() Output :Now, if we look at the dtype of each column, we can see that the column “A” and “C” are now of int64 type. DataFrame.isna() function is used to detect missing values. It return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ” or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Code #1: Use isna() function to detect the missing values in a dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf Lets use the isna() function to detect the missing values. # detect the missing valuesdf.isna() Output :In the output, cells corresponding to the missing values contains true value else false. DataFrame.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false. Code #1: Use notna() function to find all the non-missing value in the dataframe. # importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Print the dataframeprint(df) Let’s use the dataframe.notna() function to find all the non-missing values in the dataframe. # find non-na valuesdf.notna() Output :As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe. nidhi_biet 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 ? 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 | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n25 Jul, 2019" }, { "code": null, "e": 24584, "s": 24292, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. In this article, we are using “nba.csv” file to download the CSV, click here." }, { "code": null, "e": 24774, "s": 24584, "text": "DataFrame.astype() function is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type." }, { "code": null, "e": 24820, "s": 24774, "text": "Code #1: Convert the Weight column data type." }, { "code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of # the data frame for visualization df[:10]", "e": 25007, "s": 24820, "text": null }, { "code": null, "e": 25118, "s": 25007, "text": "As the data have some “nan” values so, to avoid any error we will drop all the rows containing any nan values." }, { "code": "# drop all those rows which # have any 'nan' value in it.df.dropna(inplace = True)", "e": 25201, "s": 25118, "text": null }, { "code": "# let's find out the data type of Weight columnbefore = type(df.Weight[0]) # Now we will convert it into 'int64' type.df.Weight = df.We<strong>ight.astype('int64') # let's find out the data type after castingafter = type(df.Weight[0]) # print the value of beforebefore # print the value of afterafter", "e": 25506, "s": 25201, "text": null }, { "code": null, "e": 25514, "s": 25506, "text": "Output:" }, { "code": "# print the data frame and see# what it looks like after the changedf", "e": 25584, "s": 25514, "text": null }, { "code": null, "e": 25883, "s": 25586, "text": "DataFrame.infer_objects() function attempts to infer better data type for input object column. This function attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction." }, { "code": null, "e": 25948, "s": 25883, "text": "Code #1: Use infer_objects() function to infer better data type." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[\"sofia\", 5, 8, 11, 100], \"B\":[2, 8, 77, 4, 11], \"C\":[\"amy\", 11, 4, 6, 9]}) # Print the dataframeprint(df)", "e": 26185, "s": 25948, "text": null }, { "code": null, "e": 26194, "s": 26185, "text": "Output :" }, { "code": null, "e": 26259, "s": 26194, "text": "Let’s see the dtype (data type) of each column in the dataframe." }, { "code": "# to print the basic infodf.info()", "e": 26294, "s": 26259, "text": null }, { "code": null, "e": 26469, "s": 26294, "text": "As we can see in the output, first and third column is of object type. whereas the second column is of int64 type. Now slice the dataframe and create a new dataframe from it." }, { "code": "# slice from the 1st row till enddf_new = df[1:] # Let's print the new data framedf_new # Now let's print the data type of the columnsdf_new.info()", "e": 26619, "s": 26469, "text": null }, { "code": null, "e": 26628, "s": 26619, "text": "Output :" }, { "code": null, "e": 26779, "s": 26628, "text": "As we can see in the output, column “A” and “C” are of object type even though they contain integer value. So, let’s try the infer_objects() function." }, { "code": "# applying infer_objects() function.df_new = df_new.infer_objects() # Print the dtype after applying the functiondf_new.info()", "e": 26907, "s": 26779, "text": null }, { "code": null, "e": 27023, "s": 26907, "text": "Output :Now, if we look at the dtype of each column, we can see that the column “A” and “C” are now of int64 type. " }, { "code": null, "e": 27401, "s": 27023, "text": "DataFrame.isna() function is used to detect missing values. It return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ” or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True)." }, { "code": null, "e": 27475, "s": 27401, "text": "Code #1: Use isna() function to detect the missing values in a dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf", "e": 27598, "s": 27475, "text": null }, { "code": null, "e": 27657, "s": 27598, "text": "Lets use the isna() function to detect the missing values." }, { "code": "# detect the missing valuesdf.isna()", "e": 27694, "s": 27657, "text": null }, { "code": null, "e": 27792, "s": 27694, "text": "Output :In the output, cells corresponding to the missing values contains true value else false. " }, { "code": null, "e": 28132, "s": 27792, "text": "DataFrame.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false." }, { "code": null, "e": 28214, "s": 28132, "text": "Code #1: Use notna() function to find all the non-missing value in the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first dataframe df = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Print the dataframeprint(df)", "e": 28486, "s": 28214, "text": null }, { "code": null, "e": 28580, "s": 28486, "text": "Let’s use the dataframe.notna() function to find all the non-missing values in the dataframe." }, { "code": "# find non-na valuesdf.notna()", "e": 28611, "s": 28580, "text": null }, { "code": null, "e": 28789, "s": 28611, "text": "Output :As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe. " }, { "code": null, "e": 28800, "s": 28789, "text": "nidhi_biet" }, { "code": null, "e": 28824, "s": 28800, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28838, "s": 28824, "text": "Python-pandas" }, { "code": null, "e": 28845, "s": 28838, "text": "Python" }, { "code": null, "e": 28943, "s": 28845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28975, "s": 28943, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29031, "s": 28975, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29073, "s": 29031, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29115, "s": 29073, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29137, "s": 29115, "text": "Defaultdict in Python" }, { "code": null, "e": 29176, "s": 29137, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29207, "s": 29176, "text": "Python | os.path.join() method" }, { "code": null, "e": 29262, "s": 29207, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29291, "s": 29262, "text": "Create a directory in Python" } ]
How to scroll the Page up or down in Selenium WebDriver using java?
We can scroll the page up or down in Selenium webdriver using Java. This is achieved with the help of the Actions class. First of all, we have to create an object of this Actions class and then apply the sendKeys method to it. Now, to scroll down a page, we have to pass the parameter Keys.PAGE_DOWN to this method. To again scroll up a page, we have to pass the parameter Keys.PAGE_UP to the sendKeys method. Finally, we have to use the build and perform methods to perform this action. Syntax − Actions a = new Actions(driver); //scroll down a page a.sendKeys(Keys.PAGE_DOWN).build().perform(); //scroll up a page a.sendKeys(Keys.PAGE_UP).build().perform(); Code Implementation import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Keys; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class ScrollUpDownActions{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/index.htm"); // object of Actions class to scroll up and down Actions at = new Actions(driver); at.sendKeys(Keys.PAGE_DOWN).build().perform(); //identify element on scroll down WebElement l = driver.findElement(By.linkText("Latest Courses")); String strn = l.getText(); System.out.println("Text obtained by scrolling down is :"+strn); at.sendKeys(Keys.PAGE_UP).build().perform(); //identify element on scroll up WebElement m = driver.findElement(By.tagName("h4")); String s = m.getText(); System.out.println("Text obtained by scrolling up is :"+s); driver.quit(); } }
[ { "code": null, "e": 1289, "s": 1062, "text": "We can scroll the page up or down in Selenium webdriver using Java. This is achieved with the help of the Actions class. First of all, we have to create an object of this Actions class and then apply the sendKeys method to it." }, { "code": null, "e": 1550, "s": 1289, "text": "Now, to scroll down a page, we have to pass the parameter Keys.PAGE_DOWN to this method. To again scroll up a page, we have to pass the parameter Keys.PAGE_UP to the sendKeys method. Finally, we have to use the build and perform methods to perform this action." }, { "code": null, "e": 1559, "s": 1550, "text": "Syntax −" }, { "code": null, "e": 1722, "s": 1559, "text": "Actions a = new Actions(driver);\n//scroll down a page\na.sendKeys(Keys.PAGE_DOWN).build().perform();\n//scroll up a page\na.sendKeys(Keys.PAGE_UP).build().perform();" }, { "code": null, "e": 1742, "s": 1722, "text": "Code Implementation" }, { "code": null, "e": 3112, "s": 1742, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.interactions.Action;\nimport org.openqa.selenium.interactions.Actions;\npublic class ScrollUpDownActions{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n //URL launch\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n\n // object of Actions class to scroll up and down\n Actions at = new Actions(driver);\n at.sendKeys(Keys.PAGE_DOWN).build().perform();\n\n //identify element on scroll down\n WebElement l = driver.findElement(By.linkText(\"Latest Courses\"));\n String strn = l.getText();\n System.out.println(\"Text obtained by scrolling down is :\"+strn);\n at.sendKeys(Keys.PAGE_UP).build().perform();\n\n //identify element on scroll up\n WebElement m = driver.findElement(By.tagName(\"h4\"));\n String s = m.getText();\n System.out.println(\"Text obtained by scrolling up is :\"+s);\n driver.quit();\n }\n}" } ]
Delete a CSV Column in Python - GeeksforGeeks
02 Feb, 2021 The comma-separated values ​​(CSV) file is a delimited text file that uses commas for individual values. Each line of the file is a data record in CSV. This format used for tabular data, rows, and columns, exactly like a spreadsheet. The CSV file stores data in rows and the values ​​in each row are separated with a comma(separator), also known as a delimiter. There are 2 ways to remove a column entirely from a CSV in python. Let us now focus on the techniques : With pandas library — drop() or pop()Without pandas library With pandas library — drop() or pop() Without pandas library Here, a simple CSV file is used i.e; input.csv Method 1: Using pandas library Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas consist of a drop function that is used in removing rows or columns from the CSV files. Pandas Pop() method is common in most of the data structures but the pop() method is a little different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly. Example 1: Using drop() data.drop( labels=None, axis=0, index=None, columns=None, level=None, inplace=False,errors='raise') Import PandasRead CSV FileUse drop() function for removing or deleting rows or columns from the CSV filesPrint Data Import Pandas Read CSV File Use drop() function for removing or deleting rows or columns from the CSV files Print Data Python3 # import pandas with shortcut 'pd'import pandas as pd # read_csv function which is used to read the required CSV filedata = pd.read_csv('input.csv') # display print("Original 'input.csv' CSV Data: \n")print(data) # drop function which is used in removing or deleting rows or columns from the CSV filesdata.drop('year', inplace=True, axis=1) # display print("\nCSV Data after deleting the column 'year':\n")print(data) Output: Example 2: Using pop() We can use the panda pop () method to remove columns from CSV by naming the column as an argument. Import PandasRead CSV FileUse pop() function for removing or deleting rows or columns from the CSV filesPrint Data Import Pandas Read CSV File Use pop() function for removing or deleting rows or columns from the CSV files Print Data Python3 # import pandas with shortcut 'pd'import pandas as pd # read_csv function which is used to read the required CSV filedata = pd.read_csv('input.csv') # displayprint("Original 'input.csv' CSV Data: \n")print(data) # pop function which is used in removing or deleting columns from the CSV filesdata.pop('year') # displayprint("\nCSV Data after deleting the column 'year':\n")print(data) Output: Method 2: Using CSV library Example 3: Using CSV read and write Open Input CSV file as sourceRead Source CSV FileOpen Output CSV File as a resultPut source CSV data in result CSV using indexes Open Input CSV file as source Read Source CSV File Open Output CSV File as a result Put source CSV data in result CSV using indexes Python3 # import csvimport csv # open input CSV file as source# open output CSV file as resultwith open("input.csv", "r") as source: reader = csv.reader(source) with open("output.csv", "w") as result: writer = csv.writer(result) for r in reader: # Use CSV Index to remove a column from CSV #r[3] = r['year'] writer.writerow((r[0], r[1], r[2], r[4], r[5])) Output: Picked python-csv Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n02 Feb, 2021" }, { "code": null, "e": 24263, "s": 23901, "text": "The comma-separated values ​​(CSV) file is a delimited text file that uses commas for individual values. Each line of the file is a data record in CSV. This format used for tabular data, rows, and columns, exactly like a spreadsheet. The CSV file stores data in rows and the values ​​in each row are separated with a comma(separator), also known as a delimiter." }, { "code": null, "e": 24367, "s": 24263, "text": "There are 2 ways to remove a column entirely from a CSV in python. Let us now focus on the techniques :" }, { "code": null, "e": 24427, "s": 24367, "text": "With pandas library — drop() or pop()Without pandas library" }, { "code": null, "e": 24465, "s": 24427, "text": "With pandas library — drop() or pop()" }, { "code": null, "e": 24488, "s": 24465, "text": "Without pandas library" }, { "code": null, "e": 24535, "s": 24488, "text": "Here, a simple CSV file is used i.e; input.csv" }, { "code": null, "e": 24566, "s": 24535, "text": "Method 1: Using pandas library" }, { "code": null, "e": 25173, "s": 24566, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas consist of a drop function that is used in removing rows or columns from the CSV files. Pandas Pop() method is common in most of the data structures but the pop() method is a little different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly." }, { "code": null, "e": 25197, "s": 25173, "text": "Example 1: Using drop()" }, { "code": null, "e": 25297, "s": 25197, "text": "data.drop( labels=None, axis=0, index=None, columns=None, level=None, inplace=False,errors='raise')" }, { "code": null, "e": 25413, "s": 25297, "text": "Import PandasRead CSV FileUse drop() function for removing or deleting rows or columns from the CSV filesPrint Data" }, { "code": null, "e": 25427, "s": 25413, "text": "Import Pandas" }, { "code": null, "e": 25441, "s": 25427, "text": "Read CSV File" }, { "code": null, "e": 25521, "s": 25441, "text": "Use drop() function for removing or deleting rows or columns from the CSV files" }, { "code": null, "e": 25532, "s": 25521, "text": "Print Data" }, { "code": null, "e": 25540, "s": 25532, "text": "Python3" }, { "code": "# import pandas with shortcut 'pd'import pandas as pd # read_csv function which is used to read the required CSV filedata = pd.read_csv('input.csv') # display print(\"Original 'input.csv' CSV Data: \\n\")print(data) # drop function which is used in removing or deleting rows or columns from the CSV filesdata.drop('year', inplace=True, axis=1) # display print(\"\\nCSV Data after deleting the column 'year':\\n\")print(data)", "e": 25964, "s": 25540, "text": null }, { "code": null, "e": 25972, "s": 25964, "text": "Output:" }, { "code": null, "e": 25995, "s": 25972, "text": "Example 2: Using pop()" }, { "code": null, "e": 26094, "s": 25995, "text": "We can use the panda pop () method to remove columns from CSV by naming the column as an argument." }, { "code": null, "e": 26209, "s": 26094, "text": "Import PandasRead CSV FileUse pop() function for removing or deleting rows or columns from the CSV filesPrint Data" }, { "code": null, "e": 26223, "s": 26209, "text": "Import Pandas" }, { "code": null, "e": 26237, "s": 26223, "text": "Read CSV File" }, { "code": null, "e": 26316, "s": 26237, "text": "Use pop() function for removing or deleting rows or columns from the CSV files" }, { "code": null, "e": 26327, "s": 26316, "text": "Print Data" }, { "code": null, "e": 26335, "s": 26327, "text": "Python3" }, { "code": "# import pandas with shortcut 'pd'import pandas as pd # read_csv function which is used to read the required CSV filedata = pd.read_csv('input.csv') # displayprint(\"Original 'input.csv' CSV Data: \\n\")print(data) # pop function which is used in removing or deleting columns from the CSV filesdata.pop('year') # displayprint(\"\\nCSV Data after deleting the column 'year':\\n\")print(data)", "e": 26723, "s": 26335, "text": null }, { "code": null, "e": 26731, "s": 26723, "text": "Output:" }, { "code": null, "e": 26759, "s": 26731, "text": "Method 2: Using CSV library" }, { "code": null, "e": 26795, "s": 26759, "text": "Example 3: Using CSV read and write" }, { "code": null, "e": 26924, "s": 26795, "text": "Open Input CSV file as sourceRead Source CSV FileOpen Output CSV File as a resultPut source CSV data in result CSV using indexes" }, { "code": null, "e": 26954, "s": 26924, "text": "Open Input CSV file as source" }, { "code": null, "e": 26975, "s": 26954, "text": "Read Source CSV File" }, { "code": null, "e": 27008, "s": 26975, "text": "Open Output CSV File as a result" }, { "code": null, "e": 27056, "s": 27008, "text": "Put source CSV data in result CSV using indexes" }, { "code": null, "e": 27064, "s": 27056, "text": "Python3" }, { "code": "# import csvimport csv # open input CSV file as source# open output CSV file as resultwith open(\"input.csv\", \"r\") as source: reader = csv.reader(source) with open(\"output.csv\", \"w\") as result: writer = csv.writer(result) for r in reader: # Use CSV Index to remove a column from CSV #r[3] = r['year'] writer.writerow((r[0], r[1], r[2], r[4], r[5]))", "e": 27484, "s": 27064, "text": null }, { "code": null, "e": 27492, "s": 27484, "text": "Output:" }, { "code": null, "e": 27499, "s": 27492, "text": "Picked" }, { "code": null, "e": 27510, "s": 27499, "text": "python-csv" }, { "code": null, "e": 27517, "s": 27510, "text": "Python" }, { "code": null, "e": 27615, "s": 27517, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27624, "s": 27615, "text": "Comments" }, { "code": null, "e": 27637, "s": 27624, "text": "Old Comments" }, { "code": null, "e": 27669, "s": 27637, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27725, "s": 27669, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27767, "s": 27725, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27809, "s": 27767, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27845, "s": 27809, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27867, "s": 27845, "text": "Defaultdict in Python" }, { "code": null, "e": 27906, "s": 27867, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27933, "s": 27906, "text": "Python Classes and Objects" }, { "code": null, "e": 27964, "s": 27933, "text": "Python | os.path.join() method" } ]
Spring Cloud - Synchronous Communication with Feign
In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. In this section, we will look at how services can communicate by synchronous API calls. Although this sounds simple, as part of making API calls, we need to take care of the following − Finding address of the callee − The caller service needs to know the address of the service which it wants to call. Finding address of the callee − The caller service needs to know the address of the service which it wants to call. Load balancing − The caller service can do some intelligent load balancing to spread the load across callee services. Load balancing − The caller service can do some intelligent load balancing to spread the load across callee services. Zone awareness − The caller service should preferably call the services which are in the same zone for quick responses. Zone awareness − The caller service should preferably call the services which are in the same zone for quick responses. Netflix Feign and Spring RestTemplate (along with Ribbon) are two well-known HTTP clients used for making synchronous API calls. In this tutorial, we will use Feign Client. Let us use the case of Restaurant we have been using in the previous chapters. Let us develop a Restaurant Service which has all the information about the restaurant. First, let us update the pom.xml of the service with the following dependency − <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> And then, annotate our Spring application class with the correct annotation, i.e., @EnableDiscoveryClient and @EnableFeignCLient package com.tutorialspoint; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients @EnableDiscoveryClient public class RestaurantService{ public static void main(String[] args) { SpringApplication.run(RestaurantService.class, args); } } Points to note in the above code − @ EnableDiscoveryClient − This is the same annotation which we use for reading/writing to the Eureka server. @ EnableDiscoveryClient − This is the same annotation which we use for reading/writing to the Eureka server. @EnableFeignCLient − This annotation scans our packages for enabled feign client in our code and initializes it accordingly. @EnableFeignCLient − This annotation scans our packages for enabled feign client in our code and initializes it accordingly. Once done, now let us look briefly at Feign Interfaces which we need to define the Feign clients. Using Feign Interfaces for API calls Feign client can be simply setup by defining the API calls in an interface which can be used in Feign to construct the boilerplate code required to call the APIs. For example, consider we have two services − Service A − Caller service which uses the Feign Client. Service A − Caller service which uses the Feign Client. Service B − Callee service whose API would be called by the above Feign client Service B − Callee service whose API would be called by the above Feign client The caller service, i.e., service A in this case needs to create an interface for the API which it intends to call, i.e., service B. package com.tutorialspoint; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(name = "service-B") public interface ServiceBInterface { @RequestMapping("/objects/{id}", method=GET) public ObjectOfServiceB getObjectById(@PathVariable("id") Long id); @RequestMapping("/objects/", method=POST) public void postInfo(ObjectOfServiceB b); @RequestMapping("/objects/{id}", method=PUT) public void postInfo((@PathVariable("id") Long id, ObjectOfBServiceB b); } Points to note − The @FeignClient annotates the interfaces which will be initialized by Spring Feign and can be used by rest of the code. The @FeignClient annotates the interfaces which will be initialized by Spring Feign and can be used by rest of the code. Note that the FeignClient annotation needs to contain the name of the service, this is used to discover the service address, i.e., of service B from Eureka or other discovery platforms. Note that the FeignClient annotation needs to contain the name of the service, this is used to discover the service address, i.e., of service B from Eureka or other discovery platforms. We can then define all the API function name which we plan to call from service A. This can be general HTTP calls with GET, POST, PUT, etc., verbs. We can then define all the API function name which we plan to call from service A. This can be general HTTP calls with GET, POST, PUT, etc., verbs. Once this is done, service A can simply use the following code to call the APIs of service B − @Autowired ServiceBInterface serviceB . . . ObjectOfServiceB object = serviceB. getObjectById(5); Let us look at an example, to see this in action. Example – Feign Client with Eureka Let us say we want to find restaurants which are in the same city as that of the customer. We will use the following services − Customer Service − Has all the customer information. We had defined this in Eureka Client section earlier. Customer Service − Has all the customer information. We had defined this in Eureka Client section earlier. Eureka Discovery Server − Has information about the above services. We had defined this in the Eureka Server section earlier. Eureka Discovery Server − Has information about the above services. We had defined this in the Eureka Server section earlier. Restaurant Service − New service which we will define which has all the restaurant information. Restaurant Service − New service which we will define which has all the restaurant information. Let us first add a basic controller to our Customer service − @RestController class RestaurantCustomerInstancesController { static HashMap<Long, Customer> mockCustomerData = new HashMap(); static{ mockCustomerData.put(1L, new Customer(1, "Jane", "DC")); mockCustomerData.put(2L, new Customer(2, "John", "SFO")); mockCustomerData.put(3L, new Customer(3, "Kate", "NY")); } @RequestMapping("/customer/{id}") public Customer getCustomerInfo(@PathVariable("id") Long id) { return mockCustomerData.get(id); } } We will also define a Customer.java POJO for the above controller. package com.tutorialspoint; public class Customer { private long id; private String name; private String city; public Customer() {} public Customer(long id, String name, String city) { super(); this.id = id; this.name = name; this.city = city; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } So, once this is added, let us recompile our project and execute the following query to start − java -Dapp_port=8081 -jar .\target\spring-cloud-eureka-client-1.0.jar Note − Once the Eureka server and this service is started, we should be able to see an instance of this service registered in Eureka. To see if our API works, let's hit http://localhost:8081/customer/1 We will get the following output − { "id": 1, "name": "Jane", "city": "DC" } This proves that our service is working fine. Now let us move to define the Feign client which the Restaurant service will use to get the customer city. package com.tutorialspoint; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(name = "customer-service") public interface CustomerService { @RequestMapping("/customer/{id}") public Customer getCustomerById(@PathVariable("id") Long id); } The Feign client contains the name of the service and the API call we plan to use in the Restaurant service. Finally, let us define a controller in the Restaurant service which would use the above interface. package com.tutorialspoint; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController class RestaurantController { @Autowired CustomerService customerService; static HashMap<Long, Restaurant> mockRestaurantData = new HashMap(); static{ mockRestaurantData.put(1L, new Restaurant(1, "Pandas", "DC")); mockRestaurantData.put(2L, new Restaurant(2, "Indies", "SFO")); mockRestaurantData.put(3L, new Restaurant(3, "Little Italy", "DC")); } @RequestMapping("/restaurant/customer/{id}") public List<Restaurant> getRestaurantForCustomer(@PathVariable("id") Long id) { String customerCity = customerService.getCustomerById(id).getCity(); return mockRestaurantData.entrySet().stream().filter( entry -> entry.getValue().getCity().equals(customerCity)) .map(entry -> entry.getValue()) .collect(Collectors.toList()); } } The most important line here is the following − customerService.getCustomerById(id) which is where the magic of API calling by Feign client we defined earlier happens. Let us also define the Restaurant POJO − package com.tutorialspoint; public class Restaurant { private long id; private String name; private String city; public Restaurant(long id, String name, String city) { super(); this.id = id; this.name = name; this.city = city; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } Once this is defined, let us create a simple JAR file with the following application.properties file − spring: application: name: restaurant-service server: port: ${app_port} eureka: client: serviceURL: defaultZone: http://localhost:8900/eureka Now let us a compile our project and use the following command to execute it − java -Dapp_port=8083 -jar .\target\spring-cloud-feign-client-1.0.jar In all, we have the following items running − Standalone Eureka server Standalone Eureka server Customer service Customer service Restaurant service Restaurant service We can confirm that the above are working from the dashboard on http://localhost:8900/ Now, let us try to find all the restaurants which can serve to Jane who is placed in DC. For this, first let us hit the customer service for the same: http://localhost:8080/customer/1 { "id": 1, "name": "Jane", "city": "DC" } And then, make a call to the Restaurant Service: http://localhost:8082/restaurant/customer/1 [ { "id": 1, "name": "Pandas", "city": "DC" }, { "id": 3, "name": "Little Italy", "city": "DC" } ] As we see, Jane can be served by 2 restaurants which are in DC area. Also, from the logs of the customer service, we can see − 2021-03-11 11:52:45.745 INFO 7644 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms Querying customer for id with: 1 To conclude, as we see, without writing any boilerplate code and even specifying the address of the service, we can make HTTP calls to the services. Feign client also supports zone awareness. Say, we get an incoming request for a service and we need to choose the server which should serve the request. Instead of sending and processing that request on a server which is located far, it is more fruitful to choose a server which is in the same zone. Let us now try to setup a Feign client which is zone aware. For doing that, we will use the same case as in the previous example. we will have following − A standalone Eureka server A standalone Eureka server Two instances of zone-aware Customer service (code remains same as above, we will just use the properties file mentioned in “Eureka Zone Awareness” Two instances of zone-aware Customer service (code remains same as above, we will just use the properties file mentioned in “Eureka Zone Awareness” Two instances of zone-aware Restaurant service. Two instances of zone-aware Restaurant service. Now, let us first start the customer service which are zone aware. Just to recap, here is the application property file. spring: application: name: customer-service server: port: ${app_port} eureka: instance: metadataMap: zone: ${zoneName} client: serviceURL: defaultZone: http://localhost:8900/eureka For execution, we will have two service instances running. To do that, let's open two shells and then execute the following command on one shell − java -Dapp_port=8080 -Dzone_name=USA -jar .\target\spring-cloud-eureka-client- 1.0.jar --spring.config.location=classpath:application-za.yml And execute the following on the other shell − java -Dapp_port=8081 -Dzone_name=EU -jar .\target\spring-cloud-eureka-client- 1.0.jar --spring.config.location=classpath:application-za.yml Let us now create restaurant services which are zone aware. For this, we will use the following application-za.yml spring: application: name: restaurant-service server: port: ${app_port} eureka: instance: metadataMap: zone: ${zoneName} client: serviceURL: defaultZone: http://localhost:8900/eureka For execution, we will have two service instances running. To do that, let's open two shells and then execute the following command on one shell: java -Dapp_port=8082 -Dzone_name=USA -jar .\target\spring-cloud-feign-client- 1.0.jar --spring.config.location=classpath:application-za.yml And execute following on the other shell − java -Dapp_port=8083 -Dzone_name=EU -jar .\target\spring-cloud-feign-client- 1.0.jar --spring.config.location=classpath:application-za.yml Now, we have setup two instances each of restaurant and customer service in zone-aware mode. Now, let us test this out by hitting http://localhost:8082/restaurant/customer/1 where we are hitting USA zone. [ { "id": 1, "name": "Pandas", "city": "DC" }, { "id": 3, "name": "Little Italy", "city": "DC" } ] But the more important point here to note is that the request is served by the Customer service which is present in the USA zone and not the service which is in EU zone. For example, if we hit the same API 5 times, we will see that the customer service which runs in the USA zone will have the following in the log statements − 2021-03-11 12:25:19.036 INFO 6500 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration Got request for customer with id: 1 Got request for customer with id: 1 Got request for customer with id: 1 Got request for customer with id: 1 Got request for customer with id: 1 While the customer service in EU zone does not serve any requests. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2111, "s": 1878, "text": "In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. In this section, we will look at how services can communicate by synchronous API calls." }, { "code": null, "e": 2209, "s": 2111, "text": "Although this sounds simple, as part of making API calls, we need to take care of the following −" }, { "code": null, "e": 2325, "s": 2209, "text": "Finding address of the callee − The caller service needs to know the address of the service which it wants to call." }, { "code": null, "e": 2441, "s": 2325, "text": "Finding address of the callee − The caller service needs to know the address of the service which it wants to call." }, { "code": null, "e": 2559, "s": 2441, "text": "Load balancing − The caller service can do some intelligent load balancing to spread the load across callee services." }, { "code": null, "e": 2677, "s": 2559, "text": "Load balancing − The caller service can do some intelligent load balancing to spread the load across callee services." }, { "code": null, "e": 2797, "s": 2677, "text": "Zone awareness − The caller service should preferably call the services which are in the same zone for quick responses." }, { "code": null, "e": 2917, "s": 2797, "text": "Zone awareness − The caller service should preferably call the services which are in the same zone for quick responses." }, { "code": null, "e": 3090, "s": 2917, "text": "Netflix Feign and Spring RestTemplate (along with Ribbon) are two well-known HTTP clients used for making synchronous API calls. In this tutorial, we will use Feign Client." }, { "code": null, "e": 3257, "s": 3090, "text": "Let us use the case of Restaurant we have been using in the previous chapters. Let us develop a Restaurant Service which has all the information about the restaurant." }, { "code": null, "e": 3337, "s": 3257, "text": "First, let us update the pom.xml of the service with the following dependency −" }, { "code": null, "e": 3852, "s": 3337, "text": "<dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-openfeign</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n</dependencies>" }, { "code": null, "e": 3981, "s": 3852, "text": "And then, annotate our Spring application class with the correct annotation, i.e., @EnableDiscoveryClient and @EnableFeignCLient" }, { "code": null, "e": 4474, "s": 3981, "text": "package com.tutorialspoint;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.client.discovery.EnableDiscoveryClient;\nimport org.springframework.cloud.openfeign.EnableFeignClients;\n@SpringBootApplication\n@EnableFeignClients\n@EnableDiscoveryClient\npublic class RestaurantService{\n public static void main(String[] args) {\n SpringApplication.run(RestaurantService.class, args);\n }\n}" }, { "code": null, "e": 4509, "s": 4474, "text": "Points to note in the above code −" }, { "code": null, "e": 4618, "s": 4509, "text": "@ EnableDiscoveryClient − This is the same annotation which we use for reading/writing to the Eureka server." }, { "code": null, "e": 4727, "s": 4618, "text": "@ EnableDiscoveryClient − This is the same annotation which we use for reading/writing to the Eureka server." }, { "code": null, "e": 4852, "s": 4727, "text": "@EnableFeignCLient − This annotation scans our packages for enabled feign client in our code and initializes it accordingly." }, { "code": null, "e": 4977, "s": 4852, "text": "@EnableFeignCLient − This annotation scans our packages for enabled feign client in our code and initializes it accordingly." }, { "code": null, "e": 5075, "s": 4977, "text": "Once done, now let us look briefly at Feign Interfaces which we need to define the Feign clients." }, { "code": null, "e": 5112, "s": 5075, "text": "Using Feign Interfaces for API calls" }, { "code": null, "e": 5320, "s": 5112, "text": "Feign client can be simply setup by defining the API calls in an interface which can be used in Feign to construct the boilerplate code required to call the APIs. For example, consider we have two services −" }, { "code": null, "e": 5376, "s": 5320, "text": "Service A − Caller service which uses the Feign Client." }, { "code": null, "e": 5432, "s": 5376, "text": "Service A − Caller service which uses the Feign Client." }, { "code": null, "e": 5511, "s": 5432, "text": "Service B − Callee service whose API would be called by the above Feign client" }, { "code": null, "e": 5590, "s": 5511, "text": "Service B − Callee service whose API would be called by the above Feign client" }, { "code": null, "e": 5723, "s": 5590, "text": "The caller service, i.e., service A in this case needs to create an interface for the API which it intends to call, i.e., service B." }, { "code": null, "e": 6336, "s": 5723, "text": "package com.tutorialspoint;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\n@FeignClient(name = \"service-B\")\npublic interface ServiceBInterface {\n @RequestMapping(\"/objects/{id}\", method=GET)\n public ObjectOfServiceB getObjectById(@PathVariable(\"id\") Long id);\n @RequestMapping(\"/objects/\", method=POST)\n public void postInfo(ObjectOfServiceB b);\n @RequestMapping(\"/objects/{id}\", method=PUT)\n public void postInfo((@PathVariable(\"id\") Long id, ObjectOfBServiceB b);\n}" }, { "code": null, "e": 6353, "s": 6336, "text": "Points to note −" }, { "code": null, "e": 6474, "s": 6353, "text": "The @FeignClient annotates the interfaces which will be initialized by Spring Feign and can be used by rest of the code." }, { "code": null, "e": 6595, "s": 6474, "text": "The @FeignClient annotates the interfaces which will be initialized by Spring Feign and can be used by rest of the code." }, { "code": null, "e": 6781, "s": 6595, "text": "Note that the FeignClient annotation needs to contain the name of the service, this is used to discover the service address, i.e., of service B from Eureka or other discovery platforms." }, { "code": null, "e": 6967, "s": 6781, "text": "Note that the FeignClient annotation needs to contain the name of the service, this is used to discover the service address, i.e., of service B from Eureka or other discovery platforms." }, { "code": null, "e": 7115, "s": 6967, "text": "We can then define all the API function name which we plan to call from service A. This can be general HTTP calls with GET, POST, PUT, etc., verbs." }, { "code": null, "e": 7263, "s": 7115, "text": "We can then define all the API function name which we plan to call from service A. This can be general HTTP calls with GET, POST, PUT, etc., verbs." }, { "code": null, "e": 7358, "s": 7263, "text": "Once this is done, service A can simply use the following code to call the APIs of service B −" }, { "code": null, "e": 7456, "s": 7358, "text": "@Autowired\nServiceBInterface serviceB\n.\n.\n.\nObjectOfServiceB object = serviceB. getObjectById(5);" }, { "code": null, "e": 7506, "s": 7456, "text": "Let us look at an example, to see this in action." }, { "code": null, "e": 7541, "s": 7506, "text": "Example – Feign Client with Eureka" }, { "code": null, "e": 7669, "s": 7541, "text": "Let us say we want to find restaurants which are in the same city as that of the customer. We will use the following services −" }, { "code": null, "e": 7776, "s": 7669, "text": "Customer Service − Has all the customer information. We had defined this in Eureka Client section earlier." }, { "code": null, "e": 7883, "s": 7776, "text": "Customer Service − Has all the customer information. We had defined this in Eureka Client section earlier." }, { "code": null, "e": 8009, "s": 7883, "text": "Eureka Discovery Server − Has information about the above services. We had defined this in the Eureka Server section earlier." }, { "code": null, "e": 8135, "s": 8009, "text": "Eureka Discovery Server − Has information about the above services. We had defined this in the Eureka Server section earlier." }, { "code": null, "e": 8231, "s": 8135, "text": "Restaurant Service − New service which we will define which has all the restaurant information." }, { "code": null, "e": 8327, "s": 8231, "text": "Restaurant Service − New service which we will define which has all the restaurant information." }, { "code": null, "e": 8389, "s": 8327, "text": "Let us first add a basic controller to our Customer service −" }, { "code": null, "e": 8874, "s": 8389, "text": "@RestController\nclass RestaurantCustomerInstancesController {\n static HashMap<Long, Customer> mockCustomerData = new HashMap();\n static{\n mockCustomerData.put(1L, new Customer(1, \"Jane\", \"DC\"));\n mockCustomerData.put(2L, new Customer(2, \"John\", \"SFO\"));\n mockCustomerData.put(3L, new Customer(3, \"Kate\", \"NY\"));\n }\n @RequestMapping(\"/customer/{id}\")\n public Customer getCustomerInfo(@PathVariable(\"id\") Long id) {\n return mockCustomerData.get(id);\n }\n}" }, { "code": null, "e": 8941, "s": 8874, "text": "We will also define a Customer.java POJO for the above controller." }, { "code": null, "e": 9575, "s": 8941, "text": "package com.tutorialspoint;\npublic class Customer {\n private long id;\n private String name;\n private String city;\n public Customer() {}\n public Customer(long id, String name, String city) {\n super();\n this.id = id;\n this.name = name;\n this.city = city;\n }\n public long getId() {\n return id;\n }\n public void setId(long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getCity() {\n return city;\n }\n public void setCity(String city) {\n this.city = city;\n }\n}" }, { "code": null, "e": 9671, "s": 9575, "text": "So, once this is added, let us recompile our project and execute the following query to start −" }, { "code": null, "e": 9742, "s": 9671, "text": "java -Dapp_port=8081 -jar .\\target\\spring-cloud-eureka-client-1.0.jar\n" }, { "code": null, "e": 9876, "s": 9742, "text": "Note − Once the Eureka server and this service is started, we should be able to see an instance of this service registered in Eureka." }, { "code": null, "e": 9944, "s": 9876, "text": "To see if our API works, let's hit http://localhost:8081/customer/1" }, { "code": null, "e": 9979, "s": 9944, "text": "We will get the following output −" }, { "code": null, "e": 10031, "s": 9979, "text": "{\n \"id\": 1,\n \"name\": \"Jane\",\n \"city\": \"DC\"\n}\n" }, { "code": null, "e": 10077, "s": 10031, "text": "This proves that our service is working fine." }, { "code": null, "e": 10184, "s": 10077, "text": "Now let us move to define the Feign client which the Restaurant service will use to get the customer city." }, { "code": null, "e": 10571, "s": 10184, "text": "package com.tutorialspoint;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\n@FeignClient(name = \"customer-service\")\npublic interface CustomerService {\n @RequestMapping(\"/customer/{id}\")\n public Customer getCustomerById(@PathVariable(\"id\") Long id);\n}" }, { "code": null, "e": 10680, "s": 10571, "text": "The Feign client contains the name of the service and the API call we plan to use in the Restaurant service." }, { "code": null, "e": 10779, "s": 10680, "text": "Finally, let us define a controller in the Restaurant service which would use the above interface." }, { "code": null, "e": 11930, "s": 10779, "text": "package com.tutorialspoint;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n@RestController\nclass RestaurantController {\n @Autowired\n CustomerService customerService;\n static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();\n static{\n mockRestaurantData.put(1L, new Restaurant(1, \"Pandas\", \"DC\"));\n mockRestaurantData.put(2L, new Restaurant(2, \"Indies\", \"SFO\"));\n mockRestaurantData.put(3L, new Restaurant(3, \"Little Italy\", \"DC\"));\n}\n @RequestMapping(\"/restaurant/customer/{id}\")\n public List<Restaurant> getRestaurantForCustomer(@PathVariable(\"id\") Long\nid) {\n String customerCity = customerService.getCustomerById(id).getCity();\n return mockRestaurantData.entrySet().stream().filter(\nentry -> entry.getValue().getCity().equals(customerCity))\n.map(entry -> entry.getValue())\n.collect(Collectors.toList());\n }\n}" }, { "code": null, "e": 11978, "s": 11930, "text": "The most important line here is the following −" }, { "code": null, "e": 12014, "s": 11978, "text": "customerService.getCustomerById(id)" }, { "code": null, "e": 12098, "s": 12014, "text": "which is where the magic of API calling by Feign client we defined earlier happens." }, { "code": null, "e": 12139, "s": 12098, "text": "Let us also define the Restaurant POJO −" }, { "code": null, "e": 12753, "s": 12139, "text": "package com.tutorialspoint;\npublic class Restaurant {\n private long id;\n private String name;\n private String city;\n public Restaurant(long id, String name, String city) {\n super();\n this.id = id;\n this.name = name;\n this.city = city;\n }\n public long getId() {\n return id;\n }\n public void setId(long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getCity() {\n return city;\n }\n public void setCity(String city) {\n this.city = city;\n }\n}" }, { "code": null, "e": 12856, "s": 12753, "text": "Once this is defined, let us create a simple JAR file with the following application.properties file −" }, { "code": null, "e": 13028, "s": 12856, "text": "spring:\n application:\n name: restaurant-service\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 13107, "s": 13028, "text": "Now let us a compile our project and use the following command to execute it −" }, { "code": null, "e": 13177, "s": 13107, "text": "java -Dapp_port=8083 -jar .\\target\\spring-cloud-feign-client-1.0.jar\n" }, { "code": null, "e": 13223, "s": 13177, "text": "In all, we have the following items running −" }, { "code": null, "e": 13248, "s": 13223, "text": "Standalone Eureka server" }, { "code": null, "e": 13273, "s": 13248, "text": "Standalone Eureka server" }, { "code": null, "e": 13290, "s": 13273, "text": "Customer service" }, { "code": null, "e": 13307, "s": 13290, "text": "Customer service" }, { "code": null, "e": 13326, "s": 13307, "text": "Restaurant service" }, { "code": null, "e": 13345, "s": 13326, "text": "Restaurant service" }, { "code": null, "e": 13432, "s": 13345, "text": "We can confirm that the above are working from the dashboard on http://localhost:8900/" }, { "code": null, "e": 13521, "s": 13432, "text": "Now, let us try to find all the restaurants which can serve to Jane who is placed in DC." }, { "code": null, "e": 13616, "s": 13521, "text": "For this, first let us hit the customer service for the same: http://localhost:8080/customer/1" }, { "code": null, "e": 13668, "s": 13616, "text": "{\n \"id\": 1,\n \"name\": \"Jane\",\n \"city\": \"DC\"\n}\n" }, { "code": null, "e": 13761, "s": 13668, "text": "And then, make a call to the Restaurant Service: http://localhost:8082/restaurant/customer/1" }, { "code": null, "e": 13909, "s": 13761, "text": "[\n {\n \"id\": 1,\n \"name\": \"Pandas\",\n \"city\": \"DC\"\n },\n {\n \"id\": 3,\n \"name\": \"Little Italy\",\n \"city\": \"DC\"\n }\n]\n" }, { "code": null, "e": 13978, "s": 13909, "text": "As we see, Jane can be served by 2 restaurants which are in DC area." }, { "code": null, "e": 14036, "s": 13978, "text": "Also, from the logs of the customer service, we can see −" }, { "code": null, "e": 14195, "s": 14036, "text": "2021-03-11 11:52:45.745 INFO 7644 --- [nio-8080-exec-1]\no.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms\nQuerying customer for id with: 1\n" }, { "code": null, "e": 14344, "s": 14195, "text": "To conclude, as we see, without writing any boilerplate code and even specifying the address of the service, we can make HTTP calls to the services." }, { "code": null, "e": 14645, "s": 14344, "text": "Feign client also supports zone awareness. Say, we get an incoming request for a service and we need to choose the server which should serve the request. Instead of sending and processing that request on a server which is located far, it is more fruitful to choose a server which is in the same zone." }, { "code": null, "e": 14800, "s": 14645, "text": "Let us now try to setup a Feign client which is zone aware. For doing that, we will use the same case as in the previous example. we will have following −" }, { "code": null, "e": 14827, "s": 14800, "text": "A standalone Eureka server" }, { "code": null, "e": 14854, "s": 14827, "text": "A standalone Eureka server" }, { "code": null, "e": 15002, "s": 14854, "text": "Two instances of zone-aware Customer service (code remains same as above, we will just use the properties file mentioned in “Eureka Zone Awareness”" }, { "code": null, "e": 15150, "s": 15002, "text": "Two instances of zone-aware Customer service (code remains same as above, we will just use the properties file mentioned in “Eureka Zone Awareness”" }, { "code": null, "e": 15198, "s": 15150, "text": "Two instances of zone-aware Restaurant service." }, { "code": null, "e": 15246, "s": 15198, "text": "Two instances of zone-aware Restaurant service." }, { "code": null, "e": 15367, "s": 15246, "text": "Now, let us first start the customer service which are zone aware. Just to recap, here is the application property file." }, { "code": null, "e": 15596, "s": 15367, "text": "spring:\n application:\n name: customer-service\nserver:\n port: ${app_port}\neureka:\n instance:\n metadataMap:\n zone: ${zoneName}\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 15743, "s": 15596, "text": "For execution, we will have two service instances running. To do that, let's open two shells and then execute the following command on one shell −" }, { "code": null, "e": 15885, "s": 15743, "text": "java -Dapp_port=8080 -Dzone_name=USA -jar .\\target\\spring-cloud-eureka-client-\n1.0.jar --spring.config.location=classpath:application-za.yml\n" }, { "code": null, "e": 15932, "s": 15885, "text": "And execute the following on the other shell −" }, { "code": null, "e": 16073, "s": 15932, "text": "java -Dapp_port=8081 -Dzone_name=EU -jar .\\target\\spring-cloud-eureka-client-\n1.0.jar --spring.config.location=classpath:application-za.yml\n" }, { "code": null, "e": 16188, "s": 16073, "text": "Let us now create restaurant services which are zone aware. For this, we will use the following application-za.yml" }, { "code": null, "e": 16410, "s": 16188, "text": "spring:\n application:\n name: restaurant-service\nserver:\n port: ${app_port}\neureka:\n instance:\n metadataMap:\n zone: ${zoneName}\nclient:\n serviceURL:\n defaultZone: http://localhost:8900/eureka" }, { "code": null, "e": 16556, "s": 16410, "text": "For execution, we will have two service instances running. To do that, let's open two shells and then execute the following command on one shell:" }, { "code": null, "e": 16697, "s": 16556, "text": "java -Dapp_port=8082 -Dzone_name=USA -jar .\\target\\spring-cloud-feign-client-\n1.0.jar --spring.config.location=classpath:application-za.yml\n" }, { "code": null, "e": 16740, "s": 16697, "text": "And execute following on the other shell −" }, { "code": null, "e": 16880, "s": 16740, "text": "java -Dapp_port=8083 -Dzone_name=EU -jar .\\target\\spring-cloud-feign-client-\n1.0.jar --spring.config.location=classpath:application-za.yml\n" }, { "code": null, "e": 16973, "s": 16880, "text": "Now, we have setup two instances each of restaurant and customer service in zone-aware mode." }, { "code": null, "e": 17085, "s": 16973, "text": "Now, let us test this out by hitting http://localhost:8082/restaurant/customer/1 where we are hitting USA zone." }, { "code": null, "e": 17232, "s": 17085, "text": "[\n {\n \"id\": 1,\n \"name\": \"Pandas\",\n \"city\": \"DC\"\n },\n {\n \"id\": 3,\n \"name\": \"Little Italy\",\n \"city\": \"DC\"\n }\n]" }, { "code": null, "e": 17560, "s": 17232, "text": "But the more important point here to note is that the request is served by the Customer service which is present in the USA zone and not the service which is in EU zone. For example, if we hit the same API 5 times, we will see that the customer service which runs in the USA zone will have the following in the log statements −" }, { "code": null, "e": 17879, "s": 17560, "text": "2021-03-11 12:25:19.036 INFO 6500 --- [trap-executor-0]\nc.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via\nconfiguration\nGot request for customer with id: 1\nGot request for customer with id: 1\nGot request for customer with id: 1\nGot request for customer with id: 1\nGot request for customer with id: 1" }, { "code": null, "e": 17946, "s": 17879, "text": "While the customer service in EU zone does not serve any requests." }, { "code": null, "e": 17980, "s": 17946, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 17994, "s": 17980, "text": " Karthikeya T" }, { "code": null, "e": 18027, "s": 17994, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 18042, "s": 18027, "text": " Chaand Sheikh" }, { "code": null, "e": 18077, "s": 18042, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 18089, "s": 18077, "text": " Senol Atac" }, { "code": null, "e": 18124, "s": 18089, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18136, "s": 18124, "text": " Senol Atac" }, { "code": null, "e": 18171, "s": 18136, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18183, "s": 18171, "text": " Senol Atac" }, { "code": null, "e": 18216, "s": 18183, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 18228, "s": 18216, "text": " Senol Atac" }, { "code": null, "e": 18235, "s": 18228, "text": " Print" }, { "code": null, "e": 18246, "s": 18235, "text": " Add Notes" } ]
Checking list of all available schema in SAP HANA
This can be checked using below SQL query and it will display all the available schema in HANA system. select distinct BASE_SCHEMA_NAME from "SYS"."OBJECT_DEPENDENCIES"
[ { "code": null, "e": 1165, "s": 1062, "text": "This can be checked using below SQL query and it will display all the available schema in HANA system." }, { "code": null, "e": 1231, "s": 1165, "text": "select distinct BASE_SCHEMA_NAME from \"SYS\".\"OBJECT_DEPENDENCIES\"" } ]
Implement a stack from a LinkedList in Java
A stack can be implemented using a LinkedList by managing the LinkedList as a stack. This is done by using a class Stack which contains some of the Stack methods such as push(), top(), pop() etc. A program that demonstrates this is given as follows − Live Demo import java.util.LinkedList; class Stack { private LinkedList l = new LinkedList(); public void push(Object obj) { l.addFirst(obj); } public Object top() { return l.getFirst(); } public Object pop() { return l.removeFirst(); } } public class Demo { public static void main(String[] args) { Stack s = new Stack(); s.push(5); s.push(1); s.push(3); s.push(9); s.push(7); System.out.println("The top element of the stack is: " + s.top()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The top element of the stack is: " + s.top()); } } The top element of the stack is: 7 The stack element that is popped is: 7 The stack element that is popped is: 9 The top element of the stack is: 3 Now let us understand the above program. A class Stack is created which contains some of the Stack methods such as push(), top(), pop() etc. A code snippet which demonstrates this is as follows − class Stack { private LinkedList l = new LinkedList(); public void push(Object obj) { l.addFirst(obj); } public Object top() { return l.getFirst(); } public Object pop() { return l.removeFirst(); } } In the method main(), an object s is created of the class Stack. Then this is used to push elements into the stack, display the top element and pop elements from the stack. A code snippet which demonstrates this is as follows − public static void main(String[] args) { Stack s = new Stack(); s.push(5); s.push(1); s.push(3); s.push(9); s.push(7); System.out.println("The top element of the stack is: " + s.top()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The stack element that is popped is: " + s.pop()); System.out.println("The top element of the stack is: " + s.top()); }
[ { "code": null, "e": 1258, "s": 1062, "text": "A stack can be implemented using a LinkedList by managing the LinkedList as a stack. This is done by using a class Stack which contains some of the Stack methods such as push(), top(), pop() etc." }, { "code": null, "e": 1313, "s": 1258, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 2076, "s": 1324, "text": "import java.util.LinkedList;\nclass Stack {\n private LinkedList l = new LinkedList();\n public void push(Object obj) {\n l.addFirst(obj);\n }\n public Object top() {\n return l.getFirst();\n }\n public Object pop() {\n return l.removeFirst();\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n Stack s = new Stack();\n s.push(5);\n s.push(1);\n s.push(3);\n s.push(9);\n s.push(7);\n System.out.println(\"The top element of the stack is: \" + s.top());\n System.out.println(\"The stack element that is popped is: \" + s.pop());\n System.out.println(\"The stack element that is popped is: \" + s.pop());\n System.out.println(\"The top element of the stack is: \" + s.top());\n }\n}" }, { "code": null, "e": 2224, "s": 2076, "text": "The top element of the stack is: 7\nThe stack element that is popped is: 7\nThe stack element that is popped is: 9\nThe top element of the stack is: 3" }, { "code": null, "e": 2265, "s": 2224, "text": "Now let us understand the above program." }, { "code": null, "e": 2420, "s": 2265, "text": "A class Stack is created which contains some of the Stack methods such as push(), top(), pop() etc. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2659, "s": 2420, "text": "class Stack {\n private LinkedList l = new LinkedList();\n public void push(Object obj) {\n l.addFirst(obj);\n }\n public Object top() {\n return l.getFirst();\n }\n public Object pop() {\n return l.removeFirst();\n }\n}" }, { "code": null, "e": 2887, "s": 2659, "text": "In the method main(), an object s is created of the class Stack. Then this is used to push elements into the stack, display the top element and pop elements from the stack. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 3314, "s": 2887, "text": "public static void main(String[] args) {\n Stack s = new Stack();\n s.push(5);\n s.push(1);\n s.push(3);\n s.push(9);\n s.push(7);\n System.out.println(\"The top element of the stack is: \" + s.top());\n System.out.println(\"The stack element that is popped is: \" + s.pop());\n System.out.println(\"The stack element that is popped is: \" + s.pop());\n System.out.println(\"The top element of the stack is: \" + s.top());\n}" } ]
Java Program for n-th Fibonacci numbers - GeeksforGeeks
01 Apr, 2019 In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Method 1 ( Use recursion ) // Fibonacci Series using Recursionclass Fibonacci { static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */ 34 Method 2 ( Use Dynamic Programming ) // Fibonacci Series using Dynamic Programming class Fibonacci { static int fib(int n) { /* Declare an array to store Fibonacci numbers. */ int f[] = new int[n + 1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; if (n > 0) { f[1] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i - 1] + f[i - 2]; } } return f[n]; } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishraand improved by MichaelJoshuaRamos */ 34 Method 3 ( Use Dynamic Programming with Space Optimization) // Java program for Fibonacci Series using Space// Optimized Methodclass Fibonacci { static int fib(int n) { int a = 0, b = 1, c; if (n == 0) return a; for (int i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }} // This code is contributed by Mihir Joshi 34 Method 4 (Divide and Conquer) class Fibonacci { static int fib(int n) { int F[][] = new int[][] { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } /* Helper function that calculates F[][] raise to the power n and puts the result in F[][] Note that this function is designed only for fib() and won't work as general power function */ static void power(int F[][], int n) { int i; int M[][] = new int[][] { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } /* Driver program to test above function */ public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */ 34 Method 5 (Divide and Conquer) // Fibonacci Series using Optimized Methodclass Fibonacci { /* function that returns nth Fibonacci number */ static int fib(int n) { int F[][] = new int[][] { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } /* Optimized version of power() in method 4 */ static void power(int F[][], int n) { if (n == 0 || n == 1) return; int M[][] = new int[][] { { 1, 1 }, { 1, 0 } }; power(F, n / 2); multiply(F, F); if (n % 2 != 0) multiply(F, M); } /* Driver program to test above function */ public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */ 34 Please refer complete article on Program for Fibonacci numbers for more details! Aniket Krishna MichaelJoshuaRamos Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Iterate HashMap in Java? Factory method design pattern in Java Iterate through List in Java Java Program to Remove Duplicate Elements From the Array Java program to count the occurrence of each character in a string using Hashmap Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Dijkstra's shortest path algorithm in Java using PriorityQueue How to remove all white spaces from a String in Java? Extends vs Implements in Java
[ { "code": null, "e": 24331, "s": 24303, "text": "\n01 Apr, 2019" }, { "code": null, "e": 24429, "s": 24331, "text": "In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation" }, { "code": null, "e": 24450, "s": 24429, "text": " Fn = Fn-1 + Fn-2" }, { "code": null, "e": 24467, "s": 24450, "text": "with seed values" }, { "code": null, "e": 24489, "s": 24467, "text": " F0 = 0 and F1 = 1." }, { "code": null, "e": 24516, "s": 24489, "text": "Method 1 ( Use recursion )" }, { "code": "// Fibonacci Series using Recursionclass Fibonacci { static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */", "e": 24837, "s": 24516, "text": null }, { "code": null, "e": 24841, "s": 24837, "text": "34\n" }, { "code": null, "e": 24878, "s": 24841, "text": "Method 2 ( Use Dynamic Programming )" }, { "code": "// Fibonacci Series using Dynamic Programming class Fibonacci { static int fib(int n) { /* Declare an array to store Fibonacci numbers. */ int f[] = new int[n + 1]; int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; if (n > 0) { f[1] = 1; for (i = 2; i <= n; i++) { /* Add the previous 2 numbers in the series and store it */ f[i] = f[i - 1] + f[i - 2]; } } return f[n]; } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishraand improved by MichaelJoshuaRamos */", "e": 25604, "s": 24878, "text": null }, { "code": null, "e": 25608, "s": 25604, "text": "34\n" }, { "code": null, "e": 25668, "s": 25608, "text": "Method 3 ( Use Dynamic Programming with Space Optimization)" }, { "code": "// Java program for Fibonacci Series using Space// Optimized Methodclass Fibonacci { static int fib(int n) { int a = 0, b = 1, c; if (n == 0) return a; for (int i = 2; i <= n; i++) { c = a + b; a = b; b = c; } return b; } public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }} // This code is contributed by Mihir Joshi", "e": 26130, "s": 25668, "text": null }, { "code": null, "e": 26134, "s": 26130, "text": "34\n" }, { "code": null, "e": 26164, "s": 26134, "text": "Method 4 (Divide and Conquer)" }, { "code": "class Fibonacci { static int fib(int n) { int F[][] = new int[][] { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } /* Helper function that multiplies 2 matrices F and M of size 2*2, and puts the multiplication result back to F[][] */ static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } /* Helper function that calculates F[][] raise to the power n and puts the result in F[][] Note that this function is designed only for fib() and won't work as general power function */ static void power(int F[][], int n) { int i; int M[][] = new int[][] { { 1, 1 }, { 1, 0 } }; // n - 1 times multiply the matrix to {{1, 0}, {0, 1}} for (i = 2; i <= n; i++) multiply(F, M); } /* Driver program to test above function */ public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */", "e": 27485, "s": 26164, "text": null }, { "code": null, "e": 27489, "s": 27485, "text": "34\n" }, { "code": null, "e": 27519, "s": 27489, "text": "Method 5 (Divide and Conquer)" }, { "code": "// Fibonacci Series using Optimized Methodclass Fibonacci { /* function that returns nth Fibonacci number */ static int fib(int n) { int F[][] = new int[][] { { 1, 1 }, { 1, 0 } }; if (n == 0) return 0; power(F, n - 1); return F[0][0]; } static void multiply(int F[][], int M[][]) { int x = F[0][0] * M[0][0] + F[0][1] * M[1][0]; int y = F[0][0] * M[0][1] + F[0][1] * M[1][1]; int z = F[1][0] * M[0][0] + F[1][1] * M[1][0]; int w = F[1][0] * M[0][1] + F[1][1] * M[1][1]; F[0][0] = x; F[0][1] = y; F[1][0] = z; F[1][1] = w; } /* Optimized version of power() in method 4 */ static void power(int F[][], int n) { if (n == 0 || n == 1) return; int M[][] = new int[][] { { 1, 1 }, { 1, 0 } }; power(F, n / 2); multiply(F, F); if (n % 2 != 0) multiply(F, M); } /* Driver program to test above function */ public static void main(String args[]) { int n = 9; System.out.println(fib(n)); }}/* This code is contributed by Rajat Mishra */", "e": 28673, "s": 27519, "text": null }, { "code": null, "e": 28677, "s": 28673, "text": "34\n" }, { "code": null, "e": 28758, "s": 28677, "text": "Please refer complete article on Program for Fibonacci numbers for more details!" }, { "code": null, "e": 28773, "s": 28758, "text": "Aniket Krishna" }, { "code": null, "e": 28792, "s": 28773, "text": "MichaelJoshuaRamos" }, { "code": null, "e": 28806, "s": 28792, "text": "Java Programs" }, { "code": null, "e": 28904, "s": 28806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28913, "s": 28904, "text": "Comments" }, { "code": null, "e": 28926, "s": 28913, "text": "Old Comments" }, { "code": null, "e": 28958, "s": 28926, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 28996, "s": 28958, "text": "Factory method design pattern in Java" }, { "code": null, "e": 29025, "s": 28996, "text": "Iterate through List in Java" }, { "code": null, "e": 29082, "s": 29025, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 29163, "s": 29082, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 29211, "s": 29163, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 29262, "s": 29211, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 29325, "s": 29262, "text": "Dijkstra's shortest path algorithm in Java using PriorityQueue" }, { "code": null, "e": 29379, "s": 29325, "text": "How to remove all white spaces from a String in Java?" } ]
COMPARE Instructions in 8085 - GeeksforGeeks
01 Nov, 2018 COMPARE is an important instruction widely used in 8085 microprocessor. The 8085 instruction set has two types of Compare operations: Compare with accumulator (CMP) and Compare immediate with accumulator (CPI). The microprocessor compares a data byte (or register/memory contents) with the contents of the accumulator by subtracting the data byte from (A), and indicates whether the data byte is less than, greater than or equals to the content of accumulator by modifying the flags. However, the contents are not modified. The two types of COMPARE instructions are explained briefly in the following section: Compare (register or memory) with accumulator (CMP R/M) –This is a 1-byte instruction. It compares the data byte in the register or memory with the contents of accumulator.If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset.When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then,Instruction- CMP B Before execution: A = 57, B = 62 After execution: A = 57, B = 62 Flags: As A less than B, thus CY is set and Z flag is reset.CY=1, Z=0 Compare immediate with accumulator (CPI 8-bit) –This is a 2-byte instruction, the second byte being 8-bit data. It compares the second byte with the contents of accumulator.If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset.No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let the accumulator A contains C2H. Then,Instruction- CPI C2H Before execution: A = C2, B = C2 After execution: A = C2, B = C2 Flags: As A equals to the data byte, thus Z is set and CY flag is reset.CY=0, Z=1 Compare (register or memory) with accumulator (CMP R/M) –This is a 1-byte instruction. It compares the data byte in the register or memory with the contents of accumulator.If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset.When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then,Instruction- CMP B Before execution: A = 57, B = 62 After execution: A = 57, B = 62 Flags: As A less than B, thus CY is set and Z flag is reset.CY=1, Z=0 If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset. If A less than (R/M), the CY flag is set and Zero flag is reset. If A equals to (R/M), the Zero flag is set and CY flag is reset. If A greater than (R/M), the CY and Zero flag are reset. When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction. Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then, Instruction- CMP B Before execution: A = 57, B = 62 After execution: A = 57, B = 62 Flags: As A less than B, thus CY is set and Z flag is reset. CY=1, Z=0 Compare immediate with accumulator (CPI 8-bit) –This is a 2-byte instruction, the second byte being 8-bit data. It compares the second byte with the contents of accumulator.If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset.No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let the accumulator A contains C2H. Then,Instruction- CPI C2H Before execution: A = C2, B = C2 After execution: A = C2, B = C2 Flags: As A equals to the data byte, thus Z is set and CY flag is reset.CY=0, Z=1 If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset. If A less than 8-bit data, the CY flag is set and Zero flag is reset. If A equals to 8-bit data, the Zero flag is set and CY flag is reset. If A greater than 8-bit data, the CY and Zero flag are reset. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction. Example:Let the accumulator A contains C2H. Then, Instruction- CPI C2H Before execution: A = C2, B = C2 After execution: A = C2, B = C2 Flags: As A equals to the data byte, thus Z is set and CY flag is reset. CY=0, Z=1 microprocessor Computer Organization & Architecture GATE CS microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8086 Logical and Physical Address in Operating System Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) 8085 program to add two 8 bit numbers Architecture of 8085 microprocessor Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24439, "s": 24411, "text": "\n01 Nov, 2018" }, { "code": null, "e": 24650, "s": 24439, "text": "COMPARE is an important instruction widely used in 8085 microprocessor. The 8085 instruction set has two types of Compare operations: Compare with accumulator (CMP) and Compare immediate with accumulator (CPI)." }, { "code": null, "e": 25049, "s": 24650, "text": "The microprocessor compares a data byte (or register/memory contents) with the contents of the accumulator by subtracting the data byte from (A), and indicates whether the data byte is less than, greater than or equals to the content of accumulator by modifying the flags. However, the contents are not modified. The two types of COMPARE instructions are explained briefly in the following section:" }, { "code": null, "e": 26537, "s": 25049, "text": "Compare (register or memory) with accumulator (CMP R/M) –This is a 1-byte instruction. It compares the data byte in the register or memory with the contents of accumulator.If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset.When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then,Instruction- CMP B\nBefore execution: A = 57, B = 62\nAfter execution: A = 57, B = 62 Flags: As A less than B, thus CY is set and Z flag is reset.CY=1, Z=0 Compare immediate with accumulator (CPI 8-bit) –This is a 2-byte instruction, the second byte being 8-bit data. It compares the second byte with the contents of accumulator.If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset.No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let the accumulator A contains C2H. Then,Instruction- CPI C2H\nBefore execution: A = C2, B = C2\nAfter execution: A = C2, B = C2 Flags: As A equals to the data byte, thus Z is set and CY flag is reset.CY=0, Z=1 " }, { "code": null, "e": 27318, "s": 26537, "text": "Compare (register or memory) with accumulator (CMP R/M) –This is a 1-byte instruction. It compares the data byte in the register or memory with the contents of accumulator.If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset.When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then,Instruction- CMP B\nBefore execution: A = 57, B = 62\nAfter execution: A = 57, B = 62 Flags: As A less than B, thus CY is set and Z flag is reset.CY=1, Z=0 " }, { "code": null, "e": 27503, "s": 27318, "text": "If A less than (R/M), the CY flag is set and Zero flag is reset.If A equals to (R/M), the Zero flag is set and CY flag is reset.If A greater than (R/M), the CY and Zero flag are reset." }, { "code": null, "e": 27568, "s": 27503, "text": "If A less than (R/M), the CY flag is set and Zero flag is reset." }, { "code": null, "e": 27633, "s": 27568, "text": "If A equals to (R/M), the Zero flag is set and CY flag is reset." }, { "code": null, "e": 27690, "s": 27633, "text": "If A greater than (R/M), the CY and Zero flag are reset." }, { "code": null, "e": 27872, "s": 27690, "text": "When memory is an operand, its address is specified by HL Pair. No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction." }, { "code": null, "e": 27960, "s": 27872, "text": "Example:Let register B contains data byte 62H and the accumulator A contains 57H. Then," }, { "code": null, "e": 28047, "s": 27960, "text": "Instruction- CMP B\nBefore execution: A = 57, B = 62\nAfter execution: A = 57, B = 62 " }, { "code": null, "e": 28108, "s": 28047, "text": "Flags: As A less than B, thus CY is set and Z flag is reset." }, { "code": null, "e": 28119, "s": 28108, "text": "CY=1, Z=0 " }, { "code": null, "e": 28827, "s": 28119, "text": "Compare immediate with accumulator (CPI 8-bit) –This is a 2-byte instruction, the second byte being 8-bit data. It compares the second byte with the contents of accumulator.If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset.No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction.Example:Let the accumulator A contains C2H. Then,Instruction- CPI C2H\nBefore execution: A = C2, B = C2\nAfter execution: A = C2, B = C2 Flags: As A equals to the data byte, thus Z is set and CY flag is reset.CY=0, Z=1 " }, { "code": null, "e": 29027, "s": 28827, "text": "If A less than 8-bit data, the CY flag is set and Zero flag is reset.If A equals to 8-bit data, the Zero flag is set and CY flag is reset.If A greater than 8-bit data, the CY and Zero flag are reset." }, { "code": null, "e": 29097, "s": 29027, "text": "If A less than 8-bit data, the CY flag is set and Zero flag is reset." }, { "code": null, "e": 29167, "s": 29097, "text": "If A equals to 8-bit data, the Zero flag is set and CY flag is reset." }, { "code": null, "e": 29229, "s": 29167, "text": "If A greater than 8-bit data, the CY and Zero flag are reset." }, { "code": null, "e": 29347, "s": 29229, "text": "No contents are modified; however all remaining flags (S, P, AC) are affected according to the result of subtraction." }, { "code": null, "e": 29397, "s": 29347, "text": "Example:Let the accumulator A contains C2H. Then," }, { "code": null, "e": 29485, "s": 29397, "text": "Instruction- CPI C2H\nBefore execution: A = C2, B = C2\nAfter execution: A = C2, B = C2 " }, { "code": null, "e": 29558, "s": 29485, "text": "Flags: As A equals to the data byte, thus Z is set and CY flag is reset." }, { "code": null, "e": 29569, "s": 29558, "text": "CY=0, Z=1 " }, { "code": null, "e": 29584, "s": 29569, "text": "microprocessor" }, { "code": null, "e": 29621, "s": 29584, "text": "Computer Organization & Architecture" }, { "code": null, "e": 29629, "s": 29621, "text": "GATE CS" }, { "code": null, "e": 29644, "s": 29629, "text": "microprocessor" }, { "code": null, "e": 29742, "s": 29644, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29751, "s": 29742, "text": "Comments" }, { "code": null, "e": 29764, "s": 29751, "text": "Old Comments" }, { "code": null, "e": 29785, "s": 29764, "text": "Architecture of 8086" }, { "code": null, "e": 29834, "s": 29785, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 29929, "s": 29834, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 29967, "s": 29929, "text": "8085 program to add two 8 bit numbers" }, { "code": null, "e": 30003, "s": 29967, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 30023, "s": 30003, "text": "Layers of OSI Model" }, { "code": null, "e": 30047, "s": 30023, "text": "ACID Properties in DBMS" }, { "code": null, "e": 30074, "s": 30047, "text": "Types of Operating Systems" }, { "code": null, "e": 30087, "s": 30074, "text": "TCP/IP Model" } ]
How to check if the file is empty using PowerShell?
To check if the file is empty using PowerShell, we can use the string method called IsNullorWhiteSpace(). This method provides result true if the file is empty or only contains the white spaces otherwise false. For example, We have a test2.txt text file which has whitespaces. [String]::IsNullOrWhiteSpace((Get-content C:\Test2.txt)) True But if you have a file like CSV which contains few headers but the data is empty, in that case, Get-Content will show the wrong output because it will consider headers. For example, [String]::IsNullOrWhiteSpace((Get-content C:\Temp\NewUsers.csv)) False Because the file has headers. PS C:\> Get-Content C:\Temp\NewUsers.csv Name,FirstName,Surname,EMPNumber,Country In that case, we can use the Import-CSV command inside the brackets. [String]::IsNullOrWhiteSpace((Import-Csv C:\Temp\NewUsers.csv)) True
[ { "code": null, "e": 1273, "s": 1062, "text": "To check if the file is empty using PowerShell, we can use the string method called IsNullorWhiteSpace(). This method provides result true if the file is empty or only contains the white spaces otherwise false." }, { "code": null, "e": 1339, "s": 1273, "text": "For example, We have a test2.txt text file which has whitespaces." }, { "code": null, "e": 1396, "s": 1339, "text": "[String]::IsNullOrWhiteSpace((Get-content C:\\Test2.txt))" }, { "code": null, "e": 1401, "s": 1396, "text": "True" }, { "code": null, "e": 1583, "s": 1401, "text": "But if you have a file like CSV which contains few headers but the data is empty, in that case, Get-Content will show the wrong output because it will consider headers. For example," }, { "code": null, "e": 1648, "s": 1583, "text": "[String]::IsNullOrWhiteSpace((Get-content C:\\Temp\\NewUsers.csv))" }, { "code": null, "e": 1655, "s": 1648, "text": "False\n" }, { "code": null, "e": 1685, "s": 1655, "text": "Because the file has headers." }, { "code": null, "e": 1767, "s": 1685, "text": "PS C:\\> Get-Content C:\\Temp\\NewUsers.csv Name,FirstName,Surname,EMPNumber,Country" }, { "code": null, "e": 1836, "s": 1767, "text": "In that case, we can use the Import-CSV command inside the brackets." }, { "code": null, "e": 1900, "s": 1836, "text": "[String]::IsNullOrWhiteSpace((Import-Csv C:\\Temp\\NewUsers.csv))" }, { "code": null, "e": 1905, "s": 1900, "text": "True" } ]
Deep Learning — German Traffic Sign dataset with Keras | by Navin krishnakumar | Towards Data Science
Deep Learning course offered by New York Data Science Academy is great to get you started on your journey with deep learning and also encourages you to do a full fledged deep learning project. I decided to do an image recognition challenge using the German Traffic sign data set. I have never worked on image recognition before and hence this project was a great learning experience personally. Problem Statement and Goal of the Project The German Traffic Sign Benchmark is a multi-class, single-image classification challenge held at the International Joint Conference on Neural Networks (IJCNN) 2011. benchmark.ini.rub.de Traffic sign detection is a high relevance computer vision problem and is the basis for a lot of applications in industry such as Automotive etc. Traffic signs can provide a wide range of variations between classes in terms of color, shape, and the presence of pictograms or text. In this challenge, we will develop a deep learning algorithm that will train on German traffic sign images and then classify the unlabeled traffic signs. The deep learning model will be built using Keras (high level API for tensorflow) and we will also understand various ways to preprocess images using OpenCV and also use a cloud GPU service provider. We will be working with Keras for our algorithm building. Keras was chosen as it is easy to learn and use. Keras also seamlessly integrates well with TensorFlow. After Tensorflow, Keras seems to be the framework that is widely used by the deep learning community. The Entire code for the project could be found on my GitHub account. github.com Algorithmic Process Similar to any machine learning model building process we will also be executing the same golden steps defined below Understand the dataPreprocess the dataBuild the architecture of the modelTest the modelIterate the same process until you achieve the optimal resultsDeploy the model (Not considered for this exercise) Understand the data Preprocess the data Build the architecture of the model Test the model Iterate the same process until you achieve the optimal results Deploy the model (Not considered for this exercise) Data Understanding The Image dataset consists of 43 classes (Unique traffic sign images). Training Set has 34799 Images , Test set has 12630 images and the validation set has 4410 images. # Understand the dataprint("Training Set:", len(X_train))print("Test Set:", len(y_test))print("Validation Set:", len(X_valid))print("Image Dimensions:", np.shape(X_train[1]))print("Number of classes:", len(np.unique(y_train)))n_classes = len(np.unique(y_train)) Couple of inferences from the data that we will tackle during the preprocessing stage a) Class bias issue as some classes seem to be underrepresented b) Image contrast seems to be low for lot of images Establishing a score without any preprocessing It’s always a good practice to understand where your model stands without doing any preprocessing as that would help you establish a score for your model, which you could improve upon each iteration. The evaluation metric for our model would be “accuracy” score. I had resource constraints and was running the tests model on my mac (8GB RAM) and hence used a simple“dense” or “fully” connected neural network architecture for baseline scores and other testing. Dense Network Architecture model = Sequential()model.add(Dense(128, activation='relu', input_shape=(32*32*3,)))model.add(BatchNormalization())model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dense(n_classes, activation='softmax')) The model = Sequential() statements loads the network. The input shape is 32*32*3 (as images have 3 color channels) . In Keras, there is no specific input layer command as the input shape is the implicit input layer. The number of parameters on the first layer would be 393344 ((32*32*3*128) + 128)). We can calculate the number of parameter for the other layers in the same fashion. The Activation function is “relu”. During hyperparameters optimization we can check with Tanh, Sigmoid and other activation function if they are better suited for the task. For now we stick on to “relu”. There are 4 hidden layers of 128 neurons with relu activation and after each hidden layer except the last one a dropout(50%) function is included. The output layer has the softmax activation since we are dealing with multi class classification and there are 43 classes. The model was able to achieve an accuracy score of 84% without any preprocessing. Data Preprocessing Now that we have a score at hand, lets understand if preprocessing the images would lead to a better accuracy score and help our model. Data Augmentation is used to increase the training set data. Augmenting the data is basically creating more images from the available images but with slight alteration of the images. We generally need data proportional to the parameters we feed the neural networks. I found OpenCV to be excellent for image preprocessing. Here’s the link to the general tutorials to use OpenCV with Python implementation. Some of the techniques used in the process are Rotation, Translation, Bi lateral filtering, Grayscaling and Local Histogram Equilization. opencv-python-tutroals.readthedocs.io Slight Rotation of Images: I used 10 degrees rotation of images. It would not make much sense to rotate images more than that as that might lead to wrong representations of the traffic signs. Let’s view few images after slight rotation(not that noticeable in few images also) M_rot = cv2.getRotationMatrix2D((cols/2,rows/2),10,1) Image Translation: This is a technique by which you shift the location of the image. In layman terms, if the image’s location is (x1,y1) position, after translation it is moved to (x2,y2) position. As you can see from the below images, the location is slightly moved downwards. Bilateral Filtering: Bilateral filtering is a noise reducing , edge preserving smoothening of images. Gray Scaling: Gray scaling of images is done to reduce the information provided to the pixels and also reduces complexity. def gray_scale(image): return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) Local Histogram Equalization: This is done to increase the contrast of the images as we had identified during “Data Understanding” that the images might need an increase in contrast. def local_histo_equalize(image): kernel = morp.disk(30) img_local = rank.equalize(image, selem=kernel) return img_local Here are the images after all the preprocessing. Fixing Class Bias with Data augmentation: We are set to increase to the training set images with data augmentation, it would also make sense to address the class bias issue. Hence during augmentation, all the classes were fed with 4000 images. In the original dataset Class 2 had the maximum number of training images with 2010 records. The number 4000 (Max class records * ~2)is an arbitrary number I took to make all classes have same number of records. We can definitely play around this distribution further. Here’s the code snippet that makes all the classes to have the same number of records as we need. for i in range(0,classes): class_records = np.where(y_train==i)[0].size max_records = 4000 if class_records != max_records: ovr_sample = max_records - class_records samples = X_train[np.where(y_train==i)[0]] X_aug = [] Y_aug = [i] * ovr_sample for x in range(ovr_sample): img = samples[x % class_records] trans_img = data_augment(img) X_aug.append(trans_img) X_train_final = np.concatenate((X_train_final, X_aug), axis=0) y_train_final = np.concatenate((y_train_final, Y_aug)) Y_aug_1 = Y_aug_1 + Y_aug X_aug_1 = X_aug_1 + X_aug Model Score after Data augmentation and after fixing class Bias: The same dense neural network architecture as one used above was able to better it’s accuracy score to 88.2% after data preprocessing, which suggests to us that preprocessing of the images (Augmenting the data) was worth the effort. Convolutional Neural Networks The next step in the model building journey would be to use a much sophisticated architecture to boost our model performance. Research in the field of computer vision has established that Convolutional neural networks performs exceedingly better at image recognition challenges and hence should be the first choice. Our goal from the project was to systematically build a deep learning model and understand how each step would affect the model performance. Hence CNN was not used at the first place. It’s also beyond the scope of the article to explain how CNN’s work. Here’s an intuitive article on the same. medium.freecodecamp.org Convolutional Neural Network Architecture Here’s the Convolutional neural network architecture for the model model_conv = Sequential()## If You preprocessed with gray scaling and local histogram equivalization then input_shape = (32,32,1) else (32,32,3)model_conv.add(Conv2D(32, kernel_size=(3, 3),activation='relu', input_shape=(32, 32, 1)))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Dropout(0.25))model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Dropout(0.5))model_conv.add(Flatten())model_conv.add(Dense(128, activation='relu'))model_conv.add(Dropout(0.5))model_conv.add(Dense(n_classes, activation='softmax')) There are 4 convolutional layers + Max Pooling layers . The kernel size for the convolutional layers is (3,3). The Kernel refers to the filter size. The general size used are (5,5) or (3,3). One thing to note here is that the input shape is (32,32,1). In the dense networks we had (32,32,3) as we had not done grayscaling. Since we performed grayscaling on our images, the channels value is would become one. A max pooling layer is added with a pool size of (2,2) along with Batch Normalization. Max pooling layers is used to reduce the dimensionality which helps shorten the training time and also helps reduce overfitting. Then there are also two fully connected layers before the output layer. Note here that we need to flatten the output before this layer as the input expected is one dimensional vector. Since this is a multiclass classification the solftmax activation is used. I ran the model on my computer for 100 epochs and it took 4 days to complete(was curious to know how long it runs). The model score boosted to 97.2%. Kind of explains the hype around CNN’s. Now it made more sense to either buy some GPU’s for faster processing or go to a cloud service provider to experiment different architectures. I found FloydHub to be excellent in that regard. Using Floydhub is extremely easy. We just need to upload the dataset and import the Python code through GitHub or manually upload the code. The entire code now runs in approximately 15 minutes and I can definitely test with different architectures going forward. Way Forward This experience of building a deep learning model from scratch and also follow the process to build one was a great learning experience. I am constantly learning new stuffs everyday in this journey and trying new improvements. The next few steps to implement would be Identify the best architecture along with the best hyperparameters. Also to try AlexNet or VGGNet.Use transfer learning Identify the best architecture along with the best hyperparameters. Also to try AlexNet or VGGNet. Use transfer learning
[ { "code": null, "e": 567, "s": 172, "text": "Deep Learning course offered by New York Data Science Academy is great to get you started on your journey with deep learning and also encourages you to do a full fledged deep learning project. I decided to do an image recognition challenge using the German Traffic sign data set. I have never worked on image recognition before and hence this project was a great learning experience personally." }, { "code": null, "e": 609, "s": 567, "text": "Problem Statement and Goal of the Project" }, { "code": null, "e": 775, "s": 609, "text": "The German Traffic Sign Benchmark is a multi-class, single-image classification challenge held at the International Joint Conference on Neural Networks (IJCNN) 2011." }, { "code": null, "e": 796, "s": 775, "text": "benchmark.ini.rub.de" }, { "code": null, "e": 1077, "s": 796, "text": "Traffic sign detection is a high relevance computer vision problem and is the basis for a lot of applications in industry such as Automotive etc. Traffic signs can provide a wide range of variations between classes in terms of color, shape, and the presence of pictograms or text." }, { "code": null, "e": 1431, "s": 1077, "text": "In this challenge, we will develop a deep learning algorithm that will train on German traffic sign images and then classify the unlabeled traffic signs. The deep learning model will be built using Keras (high level API for tensorflow) and we will also understand various ways to preprocess images using OpenCV and also use a cloud GPU service provider." }, { "code": null, "e": 1695, "s": 1431, "text": "We will be working with Keras for our algorithm building. Keras was chosen as it is easy to learn and use. Keras also seamlessly integrates well with TensorFlow. After Tensorflow, Keras seems to be the framework that is widely used by the deep learning community." }, { "code": null, "e": 1764, "s": 1695, "text": "The Entire code for the project could be found on my GitHub account." }, { "code": null, "e": 1775, "s": 1764, "text": "github.com" }, { "code": null, "e": 1795, "s": 1775, "text": "Algorithmic Process" }, { "code": null, "e": 1912, "s": 1795, "text": "Similar to any machine learning model building process we will also be executing the same golden steps defined below" }, { "code": null, "e": 2113, "s": 1912, "text": "Understand the dataPreprocess the dataBuild the architecture of the modelTest the modelIterate the same process until you achieve the optimal resultsDeploy the model (Not considered for this exercise)" }, { "code": null, "e": 2133, "s": 2113, "text": "Understand the data" }, { "code": null, "e": 2153, "s": 2133, "text": "Preprocess the data" }, { "code": null, "e": 2189, "s": 2153, "text": "Build the architecture of the model" }, { "code": null, "e": 2204, "s": 2189, "text": "Test the model" }, { "code": null, "e": 2267, "s": 2204, "text": "Iterate the same process until you achieve the optimal results" }, { "code": null, "e": 2319, "s": 2267, "text": "Deploy the model (Not considered for this exercise)" }, { "code": null, "e": 2338, "s": 2319, "text": "Data Understanding" }, { "code": null, "e": 2409, "s": 2338, "text": "The Image dataset consists of 43 classes (Unique traffic sign images)." }, { "code": null, "e": 2507, "s": 2409, "text": "Training Set has 34799 Images , Test set has 12630 images and the validation set has 4410 images." }, { "code": null, "e": 2769, "s": 2507, "text": "# Understand the dataprint(\"Training Set:\", len(X_train))print(\"Test Set:\", len(y_test))print(\"Validation Set:\", len(X_valid))print(\"Image Dimensions:\", np.shape(X_train[1]))print(\"Number of classes:\", len(np.unique(y_train)))n_classes = len(np.unique(y_train))" }, { "code": null, "e": 2855, "s": 2769, "text": "Couple of inferences from the data that we will tackle during the preprocessing stage" }, { "code": null, "e": 2919, "s": 2855, "text": "a) Class bias issue as some classes seem to be underrepresented" }, { "code": null, "e": 2971, "s": 2919, "text": "b) Image contrast seems to be low for lot of images" }, { "code": null, "e": 3018, "s": 2971, "text": "Establishing a score without any preprocessing" }, { "code": null, "e": 3479, "s": 3018, "text": "It’s always a good practice to understand where your model stands without doing any preprocessing as that would help you establish a score for your model, which you could improve upon each iteration. The evaluation metric for our model would be “accuracy” score. I had resource constraints and was running the tests model on my mac (8GB RAM) and hence used a simple“dense” or “fully” connected neural network architecture for baseline scores and other testing." }, { "code": null, "e": 3506, "s": 3479, "text": "Dense Network Architecture" }, { "code": null, "e": 3930, "s": 3506, "text": "model = Sequential()model.add(Dense(128, activation='relu', input_shape=(32*32*3,)))model.add(BatchNormalization())model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(128, activation='relu'))model.add(BatchNormalization())model.add(Dense(n_classes, activation='softmax'))" }, { "code": null, "e": 4314, "s": 3930, "text": "The model = Sequential() statements loads the network. The input shape is 32*32*3 (as images have 3 color channels) . In Keras, there is no specific input layer command as the input shape is the implicit input layer. The number of parameters on the first layer would be 393344 ((32*32*3*128) + 128)). We can calculate the number of parameter for the other layers in the same fashion." }, { "code": null, "e": 4518, "s": 4314, "text": "The Activation function is “relu”. During hyperparameters optimization we can check with Tanh, Sigmoid and other activation function if they are better suited for the task. For now we stick on to “relu”." }, { "code": null, "e": 4665, "s": 4518, "text": "There are 4 hidden layers of 128 neurons with relu activation and after each hidden layer except the last one a dropout(50%) function is included." }, { "code": null, "e": 4788, "s": 4665, "text": "The output layer has the softmax activation since we are dealing with multi class classification and there are 43 classes." }, { "code": null, "e": 4870, "s": 4788, "text": "The model was able to achieve an accuracy score of 84% without any preprocessing." }, { "code": null, "e": 4889, "s": 4870, "text": "Data Preprocessing" }, { "code": null, "e": 5025, "s": 4889, "text": "Now that we have a score at hand, lets understand if preprocessing the images would lead to a better accuracy score and help our model." }, { "code": null, "e": 5291, "s": 5025, "text": "Data Augmentation is used to increase the training set data. Augmenting the data is basically creating more images from the available images but with slight alteration of the images. We generally need data proportional to the parameters we feed the neural networks." }, { "code": null, "e": 5568, "s": 5291, "text": "I found OpenCV to be excellent for image preprocessing. Here’s the link to the general tutorials to use OpenCV with Python implementation. Some of the techniques used in the process are Rotation, Translation, Bi lateral filtering, Grayscaling and Local Histogram Equilization." }, { "code": null, "e": 5606, "s": 5568, "text": "opencv-python-tutroals.readthedocs.io" }, { "code": null, "e": 5882, "s": 5606, "text": "Slight Rotation of Images: I used 10 degrees rotation of images. It would not make much sense to rotate images more than that as that might lead to wrong representations of the traffic signs. Let’s view few images after slight rotation(not that noticeable in few images also)" }, { "code": null, "e": 5936, "s": 5882, "text": "M_rot = cv2.getRotationMatrix2D((cols/2,rows/2),10,1)" }, { "code": null, "e": 6214, "s": 5936, "text": "Image Translation: This is a technique by which you shift the location of the image. In layman terms, if the image’s location is (x1,y1) position, after translation it is moved to (x2,y2) position. As you can see from the below images, the location is slightly moved downwards." }, { "code": null, "e": 6316, "s": 6214, "text": "Bilateral Filtering: Bilateral filtering is a noise reducing , edge preserving smoothening of images." }, { "code": null, "e": 6439, "s": 6316, "text": "Gray Scaling: Gray scaling of images is done to reduce the information provided to the pixels and also reduces complexity." }, { "code": null, "e": 6516, "s": 6439, "text": "def gray_scale(image): return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)" }, { "code": null, "e": 6699, "s": 6516, "text": "Local Histogram Equalization: This is done to increase the contrast of the images as we had identified during “Data Understanding” that the images might need an increase in contrast." }, { "code": null, "e": 6832, "s": 6699, "text": "def local_histo_equalize(image): kernel = morp.disk(30) img_local = rank.equalize(image, selem=kernel) return img_local" }, { "code": null, "e": 6881, "s": 6832, "text": "Here are the images after all the preprocessing." }, { "code": null, "e": 7394, "s": 6881, "text": "Fixing Class Bias with Data augmentation: We are set to increase to the training set images with data augmentation, it would also make sense to address the class bias issue. Hence during augmentation, all the classes were fed with 4000 images. In the original dataset Class 2 had the maximum number of training images with 2010 records. The number 4000 (Max class records * ~2)is an arbitrary number I took to make all classes have same number of records. We can definitely play around this distribution further." }, { "code": null, "e": 7492, "s": 7394, "text": "Here’s the code snippet that makes all the classes to have the same number of records as we need." }, { "code": null, "e": 8159, "s": 7492, "text": "for i in range(0,classes): class_records = np.where(y_train==i)[0].size max_records = 4000 if class_records != max_records: ovr_sample = max_records - class_records samples = X_train[np.where(y_train==i)[0]] X_aug = [] Y_aug = [i] * ovr_sample for x in range(ovr_sample): img = samples[x % class_records] trans_img = data_augment(img) X_aug.append(trans_img) X_train_final = np.concatenate((X_train_final, X_aug), axis=0) y_train_final = np.concatenate((y_train_final, Y_aug)) Y_aug_1 = Y_aug_1 + Y_aug X_aug_1 = X_aug_1 + X_aug" }, { "code": null, "e": 8224, "s": 8159, "text": "Model Score after Data augmentation and after fixing class Bias:" }, { "code": null, "e": 8457, "s": 8224, "text": "The same dense neural network architecture as one used above was able to better it’s accuracy score to 88.2% after data preprocessing, which suggests to us that preprocessing of the images (Augmenting the data) was worth the effort." }, { "code": null, "e": 8487, "s": 8457, "text": "Convolutional Neural Networks" }, { "code": null, "e": 9097, "s": 8487, "text": "The next step in the model building journey would be to use a much sophisticated architecture to boost our model performance. Research in the field of computer vision has established that Convolutional neural networks performs exceedingly better at image recognition challenges and hence should be the first choice. Our goal from the project was to systematically build a deep learning model and understand how each step would affect the model performance. Hence CNN was not used at the first place. It’s also beyond the scope of the article to explain how CNN’s work. Here’s an intuitive article on the same." }, { "code": null, "e": 9121, "s": 9097, "text": "medium.freecodecamp.org" }, { "code": null, "e": 9163, "s": 9121, "text": "Convolutional Neural Network Architecture" }, { "code": null, "e": 9230, "s": 9163, "text": "Here’s the Convolutional neural network architecture for the model" }, { "code": null, "e": 10148, "s": 9230, "text": "model_conv = Sequential()## If You preprocessed with gray scaling and local histogram equivalization then input_shape = (32,32,1) else (32,32,3)model_conv.add(Conv2D(32, kernel_size=(3, 3),activation='relu', input_shape=(32, 32, 1)))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Dropout(0.25))model_conv.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))model_conv.add(MaxPooling2D(pool_size=(2, 2)))model.add(BatchNormalization())model_conv.add(Dropout(0.5))model_conv.add(Flatten())model_conv.add(Dense(128, activation='relu'))model_conv.add(Dropout(0.5))model_conv.add(Dense(n_classes, activation='softmax'))" }, { "code": null, "e": 10339, "s": 10148, "text": "There are 4 convolutional layers + Max Pooling layers . The kernel size for the convolutional layers is (3,3). The Kernel refers to the filter size. The general size used are (5,5) or (3,3)." }, { "code": null, "e": 10557, "s": 10339, "text": "One thing to note here is that the input shape is (32,32,1). In the dense networks we had (32,32,3) as we had not done grayscaling. Since we performed grayscaling on our images, the channels value is would become one." }, { "code": null, "e": 10773, "s": 10557, "text": "A max pooling layer is added with a pool size of (2,2) along with Batch Normalization. Max pooling layers is used to reduce the dimensionality which helps shorten the training time and also helps reduce overfitting." }, { "code": null, "e": 10957, "s": 10773, "text": "Then there are also two fully connected layers before the output layer. Note here that we need to flatten the output before this layer as the input expected is one dimensional vector." }, { "code": null, "e": 11032, "s": 10957, "text": "Since this is a multiclass classification the solftmax activation is used." }, { "code": null, "e": 11222, "s": 11032, "text": "I ran the model on my computer for 100 epochs and it took 4 days to complete(was curious to know how long it runs). The model score boosted to 97.2%. Kind of explains the hype around CNN’s." }, { "code": null, "e": 11554, "s": 11222, "text": "Now it made more sense to either buy some GPU’s for faster processing or go to a cloud service provider to experiment different architectures. I found FloydHub to be excellent in that regard. Using Floydhub is extremely easy. We just need to upload the dataset and import the Python code through GitHub or manually upload the code." }, { "code": null, "e": 11677, "s": 11554, "text": "The entire code now runs in approximately 15 minutes and I can definitely test with different architectures going forward." }, { "code": null, "e": 11689, "s": 11677, "text": "Way Forward" }, { "code": null, "e": 11957, "s": 11689, "text": "This experience of building a deep learning model from scratch and also follow the process to build one was a great learning experience. I am constantly learning new stuffs everyday in this journey and trying new improvements. The next few steps to implement would be" }, { "code": null, "e": 12077, "s": 11957, "text": "Identify the best architecture along with the best hyperparameters. Also to try AlexNet or VGGNet.Use transfer learning" }, { "code": null, "e": 12176, "s": 12077, "text": "Identify the best architecture along with the best hyperparameters. Also to try AlexNet or VGGNet." } ]
Sort array of objects by string property value - JavaScript
Suppose, we have an array of Objects like this − const arr = [ { first_name: 'Lazslo', last_name: 'Jamf' }, { first_name: 'Pig', last_name: 'Bodine' }, { first_name: 'Pirate', last_name: 'Prentice' } ]; We are required to write a JavaScript function that takes in one such array and sort this array according to the alphabetical value of the last_name key. Following is the code − const arr = [ { first_name: 'Lazslo', last_name: 'Jamf' }, { first_name: 'Pig', last_name: 'Bodine' }, { first_name: 'Pirate', last_name: 'Prentice' } ]; const sortByLastName = arr => { arr.sort((a, b) => { return a.last_name.charCodeAt(0) - b.last_name.charCodeAt(0); }); }; sortByLastName(arr); console.log(arr); This will produce the following output on console − [ { first_name: 'Pig', last_name: 'Bodine' }, { first_name: 'Lazslo', last_name: 'Jamf' }, { first_name: 'Pirate', last_name: 'Prentice' } ]
[ { "code": null, "e": 1111, "s": 1062, "text": "Suppose, we have an array of Objects like this −" }, { "code": null, "e": 1283, "s": 1111, "text": "const arr = [\n { first_name: 'Lazslo', last_name: 'Jamf' },\n { first_name: 'Pig', last_name: 'Bodine' },\n { first_name: 'Pirate', last_name: 'Prentice' }\n];" }, { "code": null, "e": 1437, "s": 1283, "text": "We are required to write a JavaScript function that takes in one such array and sort this array according to the alphabetical value of the last_name key." }, { "code": null, "e": 1461, "s": 1437, "text": "Following is the code −" }, { "code": null, "e": 1797, "s": 1461, "text": "const arr = [\n { first_name: 'Lazslo', last_name: 'Jamf' },\n { first_name: 'Pig', last_name: 'Bodine' },\n { first_name: 'Pirate', last_name: 'Prentice' }\n];\nconst sortByLastName = arr => {\n arr.sort((a, b) => {\n return a.last_name.charCodeAt(0) - b.last_name.charCodeAt(0);\n });\n};\nsortByLastName(arr);\nconsole.log(arr);" }, { "code": null, "e": 1849, "s": 1797, "text": "This will produce the following output on console −" }, { "code": null, "e": 1999, "s": 1849, "text": "[\n { first_name: 'Pig', last_name: 'Bodine' },\n { first_name: 'Lazslo', last_name: 'Jamf' },\n { first_name: 'Pirate', last_name: 'Prentice' }\n]" } ]
Flask App Routing - GeeksforGeeks
27 Oct, 2021 App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL (“/”) is associated with the root URL. So if our site’s domain was www.example.org and we want to add routing to “www.example.org/hello”, we would use “/hello”. To bind a function to an URL path we use the app.route decorator. In the below example, we have implemented the above routing in the flask. main.py from flask import Flask app = Flask(__name__) # Pass the required route to the [email protected]("/hello")def hello(): return "Hello, Welcome to GeeksForGeeks" @app.route("/")def index(): return "Homepage of GeeksForGeeks" if __name__ == "__main__": app.run(debug=True) The hello function is now mapped with the “/hello” path and we get the output of the function rendered on the browser. Step to run the application: Run the application using the following command. python main.py Output: Open the browser and visit 127.0.0.1:5000/hello, you will see the following output. Dynamic URLs – We can also build dynamic URLs by using variables in the URL. To add variables to URLs, use <variable_name> rule. The function then receives the <variable_name> as keyword argument. Example: Consider the following example to demonstrate the dynamic URLs. main.py from flask import Flask app = Flask(__name__) @app.route('/user/<username>')def show_user(username): # Greet the user return f'Hello {username} !' # Pass the required route to the [email protected]("/hello")def hello(): return "Hello, Welcome to GeeksForGeeks" @app.route("/")def index(): return "Homepage of GeeksForGeeks" if __name__ == "__main__": app.run(debug=True) Step to run the application: Run the application using the following command. python main.py Output: Open the browser and visit 127.0.0.1:5000/user/geek, you will see the following output. Additionally, we can also a converter to convert the variable to a specific data type. By default, it is set to sting values. To convert use <converter:variable_name> and following converter types are supported. sting: It is the default type and it accepts any text without a slash. int: It accepts positive integers. float: It accepts positive floating-point values. path: It is like a string but also accepts slashes. uuid: It accepts UUID strings. Example: Consider the following example to demonstrate the converter type. main.py from flask import Flask app = Flask(__name__) @app.route('/post/<int:id>')def show_post(id): # Shows the post with given id. return f'This post has the id {id}' @app.route('/user/<username>')def show_user(username): # Greet the user return f'Hello {username} !' # Pass the required route to the [email protected]("/hello")def hello(): return "Hello, Welcome to GeeksForGeeks" @app.route("/")def index(): return "Homepage of GeeksForGeeks" if __name__ == "__main__": app.run(debug=True) Step to run the application: Run the application using the following command. python main.py Output: Open the browser and visit 127.0.0.1:5000/post/13, you will see the following output. The add_url_rule() function – The URL mapping can also be done using the add_url_rule() function. This approach is mainly used in case we are importing the view function from another module. In fact, the app.route calls this function internally. Syntax: add_url_rule(<url rule>, <endpoint>, <view function>) Example: In the below example, we will try to map the show_user view function using this approach. main.py from flask import Flask app = Flask(__name__) def show_user(username): # Greet the user return f'Hello {username} !' app.add_url_rule('/user/<username>', 'show_user', show_user) if __name__ == "__main__": app.run(debug=True) Step to run the application: Run the application using the following command. python main.py Output: Open the browser and visit 127.0.0.1:5000/user/pulkit, you will see the following output. Picked Python Flask Python Web Technologies 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 Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24214, "s": 24186, "text": "\n27 Oct, 2021" }, { "code": null, "e": 24422, "s": 24214, "text": "App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. " }, { "code": null, "e": 24621, "s": 24422, "text": "Example: In our application, the URL (“/”) is associated with the root URL. So if our site’s domain was www.example.org and we want to add routing to “www.example.org/hello”, we would use “/hello”. " }, { "code": null, "e": 24761, "s": 24621, "text": "To bind a function to an URL path we use the app.route decorator. In the below example, we have implemented the above routing in the flask." }, { "code": null, "e": 24769, "s": 24761, "text": "main.py" }, { "code": "from flask import Flask app = Flask(__name__) # Pass the required route to the [email protected](\"/hello\")def hello(): return \"Hello, Welcome to GeeksForGeeks\" @app.route(\"/\")def index(): return \"Homepage of GeeksForGeeks\" if __name__ == \"__main__\": app.run(debug=True)", "e": 25057, "s": 24769, "text": null }, { "code": null, "e": 25176, "s": 25057, "text": "The hello function is now mapped with the “/hello” path and we get the output of the function rendered on the browser." }, { "code": null, "e": 25254, "s": 25176, "text": "Step to run the application: Run the application using the following command." }, { "code": null, "e": 25269, "s": 25254, "text": "python main.py" }, { "code": null, "e": 25361, "s": 25269, "text": "Output: Open the browser and visit 127.0.0.1:5000/hello, you will see the following output." }, { "code": null, "e": 25558, "s": 25361, "text": "Dynamic URLs – We can also build dynamic URLs by using variables in the URL. To add variables to URLs, use <variable_name> rule. The function then receives the <variable_name> as keyword argument." }, { "code": null, "e": 25631, "s": 25558, "text": "Example: Consider the following example to demonstrate the dynamic URLs." }, { "code": null, "e": 25639, "s": 25631, "text": "main.py" }, { "code": "from flask import Flask app = Flask(__name__) @app.route('/user/<username>')def show_user(username): # Greet the user return f'Hello {username} !' # Pass the required route to the [email protected](\"/hello\")def hello(): return \"Hello, Welcome to GeeksForGeeks\" @app.route(\"/\")def index(): return \"Homepage of GeeksForGeeks\" if __name__ == \"__main__\": app.run(debug=True)", "e": 26035, "s": 25639, "text": null }, { "code": null, "e": 26113, "s": 26035, "text": "Step to run the application: Run the application using the following command." }, { "code": null, "e": 26128, "s": 26113, "text": "python main.py" }, { "code": null, "e": 26224, "s": 26128, "text": "Output: Open the browser and visit 127.0.0.1:5000/user/geek, you will see the following output." }, { "code": null, "e": 26436, "s": 26224, "text": "Additionally, we can also a converter to convert the variable to a specific data type. By default, it is set to sting values. To convert use <converter:variable_name> and following converter types are supported." }, { "code": null, "e": 26507, "s": 26436, "text": "sting: It is the default type and it accepts any text without a slash." }, { "code": null, "e": 26542, "s": 26507, "text": "int: It accepts positive integers." }, { "code": null, "e": 26592, "s": 26542, "text": "float: It accepts positive floating-point values." }, { "code": null, "e": 26644, "s": 26592, "text": "path: It is like a string but also accepts slashes." }, { "code": null, "e": 26675, "s": 26644, "text": "uuid: It accepts UUID strings." }, { "code": null, "e": 26750, "s": 26675, "text": "Example: Consider the following example to demonstrate the converter type." }, { "code": null, "e": 26758, "s": 26750, "text": "main.py" }, { "code": "from flask import Flask app = Flask(__name__) @app.route('/post/<int:id>')def show_post(id): # Shows the post with given id. return f'This post has the id {id}' @app.route('/user/<username>')def show_user(username): # Greet the user return f'Hello {username} !' # Pass the required route to the [email protected](\"/hello\")def hello(): return \"Hello, Welcome to GeeksForGeeks\" @app.route(\"/\")def index(): return \"Homepage of GeeksForGeeks\" if __name__ == \"__main__\": app.run(debug=True)", "e": 27276, "s": 26758, "text": null }, { "code": null, "e": 27354, "s": 27276, "text": "Step to run the application: Run the application using the following command." }, { "code": null, "e": 27369, "s": 27354, "text": "python main.py" }, { "code": null, "e": 27463, "s": 27369, "text": "Output: Open the browser and visit 127.0.0.1:5000/post/13, you will see the following output." }, { "code": null, "e": 27710, "s": 27463, "text": "The add_url_rule() function – The URL mapping can also be done using the add_url_rule() function. This approach is mainly used in case we are importing the view function from another module. In fact, the app.route calls this function internally. " }, { "code": null, "e": 27718, "s": 27710, "text": "Syntax:" }, { "code": null, "e": 27773, "s": 27718, "text": "add_url_rule(<url rule>, <endpoint>, <view function>) " }, { "code": null, "e": 27872, "s": 27773, "text": "Example: In the below example, we will try to map the show_user view function using this approach." }, { "code": null, "e": 27880, "s": 27872, "text": "main.py" }, { "code": "from flask import Flask app = Flask(__name__) def show_user(username): # Greet the user return f'Hello {username} !' app.add_url_rule('/user/<username>', 'show_user', show_user) if __name__ == \"__main__\": app.run(debug=True)", "e": 28120, "s": 27880, "text": null }, { "code": null, "e": 28198, "s": 28120, "text": "Step to run the application: Run the application using the following command." }, { "code": null, "e": 28213, "s": 28198, "text": "python main.py" }, { "code": null, "e": 28311, "s": 28213, "text": "Output: Open the browser and visit 127.0.0.1:5000/user/pulkit, you will see the following output." }, { "code": null, "e": 28318, "s": 28311, "text": "Picked" }, { "code": null, "e": 28331, "s": 28318, "text": "Python Flask" }, { "code": null, "e": 28338, "s": 28331, "text": "Python" }, { "code": null, "e": 28355, "s": 28338, "text": "Web Technologies" }, { "code": null, "e": 28453, "s": 28355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28462, "s": 28453, "text": "Comments" }, { "code": null, "e": 28475, "s": 28462, "text": "Old Comments" }, { "code": null, "e": 28507, "s": 28475, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28563, "s": 28507, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28584, "s": 28563, "text": "Python OOPs Concepts" }, { "code": null, "e": 28623, "s": 28584, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28665, "s": 28623, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28707, "s": 28665, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28740, "s": 28707, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28802, "s": 28740, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28845, "s": 28802, "text": "How to fetch data from an API in ReactJS ?" } ]
Reading an image using Python OpenCv module
In OpenCv module,we can use the function cv2.imread() to read an image. When inputting the image path, the image should be in the working directory or a full path of image should be given. cv2.IMREAD_COLOR − This function loads a color image and any transparency of image will be neglected. It is the default flag. cv2.IMREAD_GRAYSCALE − This function loads image in grayscale mode cv2.IMREAD_UNCHANGED − This function loads image as such including alpha channel import numpy as np import cv2 my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg', 0) cv2.imshow('image', my_img) k = cv2.waitKey(0) & 0xFF # wait for ESC key to exit if k == 27: cv2.destroyAllWindows() elif k == ord('s'): cv2.imwrite('C:/Users/TP/Desktop/poor/poverty_india_gray.jpg',my_img) cv2.destroyAllWindows() import cv2 import numpy as np import matplotlib.pyplot as plt my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg',cv2.IMREAD_GRAYSCALE) cv2.imshow('image', my_img) cv2.waitKey(0) cv2.destoryAllWindows()
[ { "code": null, "e": 1251, "s": 1062, "text": "In OpenCv module,we can use the function cv2.imread() to read an image. When inputting the image path, the image should be in the working directory or a full path of image should be given." }, { "code": null, "e": 1377, "s": 1251, "text": "cv2.IMREAD_COLOR − This function loads a color image and any transparency of image will be neglected. It is the default flag." }, { "code": null, "e": 1444, "s": 1377, "text": "cv2.IMREAD_GRAYSCALE − This function loads image in grayscale mode" }, { "code": null, "e": 1525, "s": 1444, "text": "cv2.IMREAD_UNCHANGED − This function loads image as such including alpha channel" }, { "code": null, "e": 1864, "s": 1525, "text": "import numpy as np\nimport cv2\nmy_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg', 0)\ncv2.imshow('image', my_img)\nk = cv2.waitKey(0) & 0xFF\n# wait for ESC key to exit\nif k == 27:\n cv2.destroyAllWindows()\nelif k == ord('s'):\n cv2.imwrite('C:/Users/TP/Desktop/poor/poverty_india_gray.jpg',my_img)\n cv2.destroyAllWindows()" }, { "code": null, "e": 2080, "s": 1864, "text": "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nmy_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg',cv2.IMREAD_GRAYSCALE)\ncv2.imshow('image', my_img)\ncv2.waitKey(0)\ncv2.destoryAllWindows()" } ]
How to know which storage engine is used in MongoDB?
To know which storage engine is used in MongoDB, you can use storageEngine. The syntax is as follows − db.serverStatus().storageEngine; To know all the configuration details of storage engine, you can use the following syntax: db.serverStatus().yourStorageEngineName; Let us implement the above syntax to know which storage engine is being used in MongoDB. The query is as follows − > db.serverStatus().storageEngine; The following is the output − { "name" : "wiredTiger", "supportsCommittedReads" : true, "supportsSnapshotReadConcern" : true, "readOnly" : false, "persistent" : true } In order to know all configuration details about the above storage engine, the query is as follows − > db.serverStatus().wiredTiger; The following is the output displaying configuration details − { "uri" : "statistics:", "LSM" : { "application work units currently queued" : 0, "merge work units currently queued" : 0, "rows merged in an LSM tree" : 0, "sleep for LSM checkpoint throttle" : 0, "sleep for LSM merge throttle" : 0, "switch work units currently queued" : 0, "tree maintenance operations discarded" : 0, "tree maintenance operations executed" : 0, "tree maintenance operations scheduled" : 0, "tree queue hit maximum" : 0 }, "async" : { "current work queue length" : 0, "maximum work queue length" : 0, "number of allocation state races" : 0, "number of flush calls" : 0, "number of operation slots viewed for allocation" : 0, "number of times operation allocation failed" : 0, "number of times worker found no work" : 0, "total allocations" : 0, "total compact calls" : 0, "total insert calls" : 0, "total remove calls" : 0, "total search calls" : 0, "total update calls" : 0 }, "block-manager" : { "blocks pre-loaded" : 173, "blocks read" : 482, "blocks written" : 312, "bytes read" : 2400256, "bytes written" : 2953216, "bytes written for checkpoint" : 2953216, "mapped blocks read" : 0, "mapped bytes read" : 0 }, "cache" : { "application threads page read from disk to cache count" : 157, "application threads page read from disk to cache time (usecs)" : 58747, "application threads page write from cache to disk count" : 172, "application threads page write from cache to disk time (usecs)" : 37010, "bytes belonging to page images in the cache" : 663718, "bytes belonging to the cache overflow table in the cache" : 182, "bytes currently in the cache" : 814060, "bytes dirty in the cache cumulative" : 2673442, "bytes not belonging to page images in the cache" : 150342, "bytes read into cache" : 614554, "bytes written from cache" : 1910375, "cache overflow cursor application thread wait time (usecs)" : 0, "cache overflow cursor internal thread wait time (usecs)" : 0, "cache overflow score" : 0, "cache overflow table entries" : 0, "cache overflow table insert calls" : 0, "cache overflow table remove calls" : 0, "checkpoint blocked page eviction" : 0, "eviction calls to get a page" : 546, "eviction calls to get a page found queue empty" : 547, "eviction calls to get a page found queue empty after locking" : 0, "eviction currently operating in aggressive mode" : 0, "eviction empty score" : 0, "eviction passes of a file" : 0, "eviction server candidate queue empty when topping up" : 0, "eviction server candidate queue not empty when topping up" : 0, "eviction server evicting pages" : 0, "eviction server slept, because we did not make progress with eviction" : 367, "eviction server unable to reach eviction goal" : 0, "eviction state" : 32, "eviction walk target pages histogram - 0-9" : 0, "eviction walk target pages histogram - 10-31" : 0, "eviction walk target pages histogram - 128 and higher" : 0, "eviction walk target pages histogram - 32-63" : 0, "eviction walk target pages histogram - 64-128" : 0, "eviction walks abandoned" : 0, "eviction walks gave up because they restarted their walk twice" : 0, "eviction walks gave up because they saw too many pages and found no candidates" : 0, "eviction walks gave up because they saw too many pages and found too few candidates" : 0, "eviction walks reached end of tree" : 0, "eviction walks started from root of tree" : 0, "eviction walks started from saved location in tree" : 0, "eviction worker thread active" : 4, "eviction worker thread created" : 0, "eviction worker thread evicting pages" : 2, "eviction worker thread removed" : 0, "eviction worker thread stable number" : 0, "failed eviction of pages that exceeded the in-memory maximum count" : 0, "failed eviction of pages that exceeded the in-memory maximum time (usecs)" : 0, "files with active eviction walks" : 0, "files with new eviction walks started" : 0, "force re-tuning of eviction workers once in a while" : 0, "hazard pointer blocked page eviction" : 0, "hazard pointer check calls" : 2, "hazard pointer check entries walked" : 0, "hazard pointer maximum array length" : 0, "in-memory page passed criteria to be split" : 0, "in-memory page splits" : 0, "internal pages evicted" : 0, "internal pages split during eviction" : 0, "leaf pages split during eviction" : 0, "maximum bytes configured" : 4803526656, "maximum page size at eviction" : 0, "modified pages evicted" : 2, "modified pages evicted by application threads" : 0, "operations timed out waiting for space in cache" : 0, "overflow pages read into cache" : 0, "page split during eviction deepened the tree" : 0, "page written requiring cache overflow records" : 0, "pages currently held in the cache" : 349, "pages evicted because they exceeded the in-memory maximum count" : 0, "pages evicted because they exceeded the in-memory maximum time (usecs)" : 0, "pages evicted because they had chains of deleted items count" : 0, "pages evicted because they had chains of deleted items time (usecs)" : 0, "pages evicted by application threads" : 0, "pages queued for eviction" : 0, "pages queued for urgent eviction" : 2, "pages queued for urgent eviction during walk" : 0, "pages read into cache" : 324, "pages read into cache after truncate" : 11, "pages read into cache after truncate in prepare state" : 0, "pages read into cache requiring cache overflow entries" : 0, "pages read into cache requiring cache overflow for checkpoint" : 0, "pages read into cache skipping older cache overflow entries" : 0, "pages read into cache with skipped cache overflow entries needed later" : 0, "pages read into cache with skipped cache overflow entries needed later by checkpoint" : 0, "pages requested from the cache" : 46897, "pages seen by eviction walk" : 0, "pages selected for eviction unable to be evicted" : 0, "pages walked for eviction" : 0, "pages written from cache" : 175, "pages written requiring in-memory restoration" : 0, "percentage overhead" : 8, "tracked bytes belonging to internal pages in the cache" : 40080, "tracked bytes belonging to leaf pages in the cache" : 773980, "tracked dirty bytes in the cache" : 0, "tracked dirty pages in the cache" : 0, "unmodified pages evicted" : 0 }, "connection" : { "auto adjusting condition resets" : 561, "auto adjusting condition wait calls" : 42647, "detected system time went backwards" : 0, "files currently open" : 170, "memory allocations" : 277416, "memory frees" : 266135, "memory re-allocations" : 23688, "pthread mutex condition wait calls" : 116127, "pthread mutex shared lock read-lock calls" : 140031, "pthread mutex shared lock write-lock calls" : 10159, "total fsync I/Os" : 760, "total read I/Os" : 2257, "total write I/Os" : 875 }, "cursor" : { "cursor close calls that result in cache" : 482, "cursor create calls" : 536, "cursor insert calls" : 296, "cursor modify calls" : 0, "cursor next calls" : 2968, "cursor operation restarted" : 0, "cursor prev calls" : 212, "cursor remove calls" : 9, "cursor reserve calls" : 0, "cursor reset calls" : 46322, "cursor search calls" : 27066, "cursor search near calls" : 441, "cursor sweep buckets" : 41532, "cursor sweep cursors closed" : 0, "cursor sweep cursors examined" : 13338, "cursor sweeps" : 6922, "cursor update calls" : 0, "cursors currently cached" : 170, "cursors reused from cache" : 312, "truncate calls" : 0 }, "data-handle" : { "connection data handles currently active" : 489, "connection sweep candidate became referenced" : 0, "connection sweep dhandles closed" : 0, "connection sweep dhandles removed from hash list" : 207, "connection sweep time-of-death sets" : 972, "connection sweeps" : 3469, "session dhandles swept" : 0, "session sweep attempts" : 373 }, "lock" : { "checkpoint lock acquisitions" : 437, "checkpoint lock application thread wait time (usecs)" : 0, "checkpoint lock internal thread wait time (usecs)" : 0, "commit timestamp queue lock application thread time waiting (usecs)" : 0, "commit timestamp queue lock internal thread time waiting (usecs)" : 0, "commit timestamp queue read lock acquisitions" : 0, "commit timestamp queue write lock acquisitions" : 0, "dhandle lock application thread time waiting (usecs)" : 0, "dhandle lock internal thread time waiting (usecs)" : 0, "dhandle read lock acquisitions" : 28619, "dhandle write lock acquisitions" : 909, "metadata lock acquisitions" : 116, "metadata lock application thread wait time (usecs)" : 0, "metadata lock internal thread wait time (usecs)" : 0, "read timestamp queue lock application thread time waiting (usecs)" : 0, "read timestamp queue lock internal thread time waiting (usecs)" : 0, "read timestamp queue read lock acquisitions" : 0, "read timestamp queue write lock acquisitions" : 0, "schema lock acquisitions" : 613, "schema lock application thread wait time (usecs)" : 0, "schema lock internal thread wait time (usecs)" : 0, "table lock application thread time waiting for the table lock (usecs)" : 0, "table lock internal thread time waiting for the table lock (usecs)" : 0, "table read lock acquisitions" : 0, "table write lock acquisitions" : 645, "txn global lock application thread time waiting (usecs)" : 0, "txn global lock internal thread time waiting (usecs)" : 0, "txn global read lock acquisitions" : 375, "txn global write lock acquisitions" : 354 }, "log" : { "busy returns attempting to switch slots" : 1, "force archive time sleeping (usecs)" : 0, "log bytes of payload data" : 49104, "log bytes written" : 105216, "log files manually zero-filled" : 0, "log flush operations" : 68872, "log force write operations" : 75951, "log force write operations skipped" : 75776, "log records compressed" : 36, "log records not compressed" : 23, "log records too small to compress" : 493, "log release advances write LSN" : 353, "log scan operations" : 4, "log scan records requiring two reads" : 3, "log server thread advances write LSN" : 175, "log server thread write LSN walk skipped" : 8776, "log sync operations" : 528, "log sync time duration (usecs)" : 29656979, "log sync_dir operations" : 1, "log sync_dir time duration (usecs)" : 0, "log write operations" : 552, "logging bytes consolidated" : 104704, "maximum log file size" : 104857600, "number of pre-allocated log files to create" : 2, "pre-allocated log files not ready and missed" : 1, "pre-allocated log files prepared" : 2, "pre-allocated log files used" : 0, "records processed by log scan" : 636, "slot close lost race" : 0, "slot close unbuffered waits" : 0, "slot closures" : 528, "slot join atomic update races" : 0, "slot join calls atomic updates raced" : 0, "slot join calls did not yield" : 552, "slot join calls found active slot closed" : 0, "slot join calls slept" : 0, "slot join calls yielded" : 0, "slot join found active slot closed" : 0, "slot joins yield time (usecs)" : 0, "slot transitions unable to find free slot" : 0, "slot unbuffered writes" : 0, "total in-memory size of compressed records" : 79123, "total log buffer size" : 33554432, "total size of compressed records" : 33250, "written slots coalesced" : 0, "yields waiting for previous log file close" : 0 }, "perf" : { "file system read latency histogram (bucket 1) - 10-49ms" : 5, "file system read latency histogram (bucket 2) - 50-99ms" : 0, "file system read latency histogram (bucket 3) - 100-249ms" : 0, "file system read latency histogram (bucket 4) - 250-499ms" : 0, "file system read latency histogram (bucket 5) - 500-999ms" : 0, "file system read latency histogram (bucket 6) - 1000ms+" : 0, "file system write latency histogram (bucket 1) - 10-49ms" : 9, "file system write latency histogram (bucket 2) - 50-99ms" : 0, "file system write latency histogram (bucket 3) - 100-249ms" : 0, "file system write latency histogram (bucket 4) - 250-499ms" : 0, "file system write latency histogram (bucket 5) - 500-999ms" : 0, "file system write latency histogram (bucket 6) - 1000ms+" : 0, "operation read latency histogram (bucket 1) - 100-249us" : 0, "operation read latency histogram (bucket 2) - 250-499us" : 0, "operation read latency histogram (bucket 3) - 500-999us" : 44, "operation read latency histogram (bucket 4) - 1000-9999us" : 20, "operation read latency histogram (bucket 5) - 10000us+" : 2, "operation write latency histogram (bucket 1) - 100-249us" : 0, "operation write latency histogram (bucket 2) - 250-499us" : 0, "operation write latency histogram (bucket 3) - 500-999us" : 7, "operation write latency histogram (bucket 4) - 1000-9999us" : 1, "operation write latency histogram (bucket 5) - 10000us+" : 1 }, "reconciliation" : { "fast-path pages deleted" : 0, "page reconciliation calls" : 193, "page reconciliation calls for eviction" : 1, "pages deleted" : 18, "split bytes currently awaiting free" : 0, "split objects currently awaiting free" : 0 }, "session" : { "open cursor count" : 22, "open session count" : 19, "session query timestamp calls" : 0, "table alter failed calls" : 0, "table alter successful calls" : 321, "table alter unchanged and skipped" : 963, "table compact failed calls" : 0, "table compact successful calls" : 0, "table create failed calls" : 0, "table create successful calls" : 7, "table drop failed calls" : 0, "table drop successful calls" : 0, "table rebalance failed calls" : 0, "table rebalance successful calls" : 0, "table rename failed calls" : 0, "table rename successful calls" : 0, "table salvage failed calls" : 0, "table salvage successful calls" : 0, "table truncate failed calls" : 0, "table truncate successful calls" : 0, "table verify failed calls" : 0, "table verify successful calls" : 0 }, "thread-state" : { "active filesystem fsync calls" : 0, "active filesystem read calls" : 0, "active filesystem write calls" : 0 }, "thread-yield" : { "application thread time evicting (usecs)" : 0, "application thread time waiting for cache (usecs)" : 0, "connection close blocked waiting for transaction state stabilization" : 0, "connection close yielded for lsm manager shutdown" : 0, "data handle lock yielded" : 0, "get reference for page index and slot time sleeping (usecs)" : 0, "log server sync yielded for log write" : 0, "page access yielded due to prepare state change" : 0, "page acquire busy blocked" : 0, "page acquire eviction blocked" : 0, "page acquire locked blocked" : 0, "page acquire read blocked" : 0, "page acquire time sleeping (usecs)" : 0, "page delete rollback time sleeping for state change (usecs)" : 0, "page reconciliation yielded due to child modification" : 0 }, "transaction" : { "Number of prepared updates" : 0, "Number of prepared updates added to cache overflow" : 0, "Number of prepared updates resolved" : 0, "commit timestamp queue entries walked" : 0, "commit timestamp queue insert to empty" : 0, "commit timestamp queue inserts to head" : 0, "commit timestamp queue inserts total" : 0, "commit timestamp queue length" : 0, "number of named snapshots created" : 0, "number of named snapshots dropped" : 0, "prepared transactions" : 0, "prepared transactions committed" : 0, "prepared transactions currently active" : 0, "prepared transactions rolled back" : 0, "query timestamp calls" : 1, "read timestamp queue entries walked" : 0, "read timestamp queue insert to empty" : 0, "read timestamp queue inserts to head" : 0, "read timestamp queue inserts total" : 0, "read timestamp queue length" : 0, "rollback to stable calls" : 0, "rollback to stable updates aborted" : 0, "rollback to stable updates removed from cache overflow" : 0, "set timestamp calls" : 0, "set timestamp commit calls" : 0, "set timestamp commit updates" : 0, "set timestamp oldest calls" : 0, "set timestamp oldest updates" : 0, "set timestamp stable calls" : 0, "set timestamp stable updates" : 0, "transaction begins" : 309, "transaction checkpoint currently running" : 0, "transaction checkpoint generation" : 117, "transaction checkpoint max time (msecs)" : 2264, "transaction checkpoint min time (msecs)" : 4, "transaction checkpoint most recent time (msecs)" : 43, "transaction checkpoint scrub dirty target" : 0, "transaction checkpoint scrub time (msecs)" : 0, "transaction checkpoint total time (msecs)" : 15771, "transaction checkpoints" : 116, "transaction checkpoints skipped because database was clean" : 0, "transaction failures due to cache overflow" : 0, "transaction fsync calls for checkpoint after allocating the transaction ID" : 116, "transaction fsync duration for checkpoint after allocating the transaction ID (usecs)" : 0, "transaction range of IDs currently pinned" : 0, "transaction range of IDs currently pinned by a checkpoint" : 0, "transaction range of IDs currently pinned by named snapshots" : 0, "transaction range of timestamps currently pinned" : 0, "transaction range of timestamps pinned by a checkpoint" : 0, "transaction range of timestamps pinned by the oldest timestamp" : 0, "transaction sync calls" : 0, "transactions committed" : 40, "transactions rolled back" : 269, "update conflicts" : 0 }, "concurrentTransactions" : { "write" : { "out" : 0, "available" : 128, "totalTickets" : 128 }, "read" : { "out" : 1, "available" : 127, "totalTickets" : 128 } } }
[ { "code": null, "e": 1165, "s": 1062, "text": "To know which storage engine is used in MongoDB, you can use storageEngine. The syntax is as follows −" }, { "code": null, "e": 1198, "s": 1165, "text": "db.serverStatus().storageEngine;" }, { "code": null, "e": 1289, "s": 1198, "text": "To know all the configuration details of storage engine, you can use the following syntax:" }, { "code": null, "e": 1330, "s": 1289, "text": "db.serverStatus().yourStorageEngineName;" }, { "code": null, "e": 1445, "s": 1330, "text": "Let us implement the above syntax to know which storage engine is being used in MongoDB. The query is as follows −" }, { "code": null, "e": 1480, "s": 1445, "text": "> db.serverStatus().storageEngine;" }, { "code": null, "e": 1510, "s": 1480, "text": "The following is the output −" }, { "code": null, "e": 1663, "s": 1510, "text": "{\n \"name\" : \"wiredTiger\",\n \"supportsCommittedReads\" : true,\n \"supportsSnapshotReadConcern\" : true,\n \"readOnly\" : false,\n \"persistent\" : true\n}" }, { "code": null, "e": 1764, "s": 1663, "text": "In order to know all configuration details about the above storage engine, the query is as follows −" }, { "code": null, "e": 1796, "s": 1764, "text": "> db.serverStatus().wiredTiger;" }, { "code": null, "e": 1859, "s": 1796, "text": "The following is the output displaying configuration details −" }, { "code": null, "e": 21228, "s": 1859, "text": "{\n \"uri\" : \"statistics:\",\n \"LSM\" : {\n \"application work units currently queued\" : 0,\n \"merge work units currently queued\" : 0,\n \"rows merged in an LSM tree\" : 0,\n \"sleep for LSM checkpoint throttle\" : 0,\n \"sleep for LSM merge throttle\" : 0,\n \"switch work units currently queued\" : 0,\n \"tree maintenance operations discarded\" : 0,\n \"tree maintenance operations executed\" : 0,\n \"tree maintenance operations scheduled\" : 0,\n \"tree queue hit maximum\" : 0\n },\n \"async\" : {\n \"current work queue length\" : 0,\n \"maximum work queue length\" : 0,\n \"number of allocation state races\" : 0,\n \"number of flush calls\" : 0,\n \"number of operation slots viewed for allocation\" : 0,\n \"number of times operation allocation failed\" : 0,\n \"number of times worker found no work\" : 0,\n \"total allocations\" : 0,\n \"total compact calls\" : 0,\n \"total insert calls\" : 0,\n \"total remove calls\" : 0,\n \"total search calls\" : 0,\n \"total update calls\" : 0\n },\n \"block-manager\" : {\n \"blocks pre-loaded\" : 173,\n \"blocks read\" : 482,\n \"blocks written\" : 312,\n \"bytes read\" : 2400256,\n \"bytes written\" : 2953216,\n \"bytes written for checkpoint\" : 2953216,\n \"mapped blocks read\" : 0,\n \"mapped bytes read\" : 0\n },\n \"cache\" : {\n \"application threads page read from disk to cache count\" : 157,\n \"application threads page read from disk to cache time (usecs)\" : 58747,\n \"application threads page write from cache to disk count\" : 172,\n \"application threads page write from cache to disk time (usecs)\" : 37010,\n \"bytes belonging to page images in the cache\" : 663718,\n \"bytes belonging to the cache overflow table in the cache\" : 182,\n \"bytes currently in the cache\" : 814060,\n \"bytes dirty in the cache cumulative\" : 2673442,\n \"bytes not belonging to page images in the cache\" : 150342,\n \"bytes read into cache\" : 614554,\n \"bytes written from cache\" : 1910375,\n \"cache overflow cursor application thread wait time (usecs)\" : 0,\n \"cache overflow cursor internal thread wait time (usecs)\" : 0,\n \"cache overflow score\" : 0,\n \"cache overflow table entries\" : 0,\n \"cache overflow table insert calls\" : 0,\n \"cache overflow table remove calls\" : 0,\n \"checkpoint blocked page eviction\" : 0,\n \"eviction calls to get a page\" : 546,\n \"eviction calls to get a page found queue empty\" : 547,\n \"eviction calls to get a page found queue empty after locking\" : 0,\n \"eviction currently operating in aggressive mode\" : 0,\n \"eviction empty score\" : 0,\n \"eviction passes of a file\" : 0,\n \"eviction server candidate queue empty when topping up\" : 0,\n \"eviction server candidate queue not empty when topping up\" : 0,\n \"eviction server evicting pages\" : 0,\n \"eviction server slept, because we did not make progress with eviction\" : 367,\n \"eviction server unable to reach eviction goal\" : 0,\n \"eviction state\" : 32,\n \"eviction walk target pages histogram - 0-9\" : 0,\n \"eviction walk target pages histogram - 10-31\" : 0,\n \"eviction walk target pages histogram - 128 and higher\" : 0,\n \"eviction walk target pages histogram - 32-63\" : 0,\n \"eviction walk target pages histogram - 64-128\" : 0,\n \"eviction walks abandoned\" : 0,\n \"eviction walks gave up because they restarted their walk twice\" : 0,\n \"eviction walks gave up because they saw too many pages and found no candidates\" : 0,\n \"eviction walks gave up because they saw too many pages and found too few candidates\" : 0,\n \"eviction walks reached end of tree\" : 0,\n \"eviction walks started from root of tree\" : 0,\n \"eviction walks started from saved location in tree\" : 0,\n \"eviction worker thread active\" : 4,\n \"eviction worker thread created\" : 0,\n \"eviction worker thread evicting pages\" : 2,\n \"eviction worker thread removed\" : 0,\n \"eviction worker thread stable number\" : 0,\n \"failed eviction of pages that exceeded the in-memory maximum count\" : 0,\n \"failed eviction of pages that exceeded the in-memory maximum time (usecs)\" : 0,\n \"files with active eviction walks\" : 0,\n \"files with new eviction walks started\" : 0,\n \"force re-tuning of eviction workers once in a while\" : 0,\n \"hazard pointer blocked page eviction\" : 0,\n \"hazard pointer check calls\" : 2,\n \"hazard pointer check entries walked\" : 0,\n \"hazard pointer maximum array length\" : 0,\n \"in-memory page passed criteria to be split\" : 0,\n \"in-memory page splits\" : 0,\n \"internal pages evicted\" : 0,\n \"internal pages split during eviction\" : 0,\n \"leaf pages split during eviction\" : 0,\n \"maximum bytes configured\" : 4803526656,\n \"maximum page size at eviction\" : 0,\n \"modified pages evicted\" : 2,\n \"modified pages evicted by application threads\" : 0,\n \"operations timed out waiting for space in cache\" : 0,\n \"overflow pages read into cache\" : 0,\n \"page split during eviction deepened the tree\" : 0,\n \"page written requiring cache overflow records\" : 0,\n \"pages currently held in the cache\" : 349,\n \"pages evicted because they exceeded the in-memory maximum count\" : 0,\n \"pages evicted because they exceeded the in-memory maximum time (usecs)\" : 0,\n \"pages evicted because they had chains of deleted items count\" : 0,\n \"pages evicted because they had chains of deleted items time (usecs)\" : 0,\n \"pages evicted by application threads\" : 0,\n \"pages queued for eviction\" : 0,\n \"pages queued for urgent eviction\" : 2,\n \"pages queued for urgent eviction during walk\" : 0,\n \"pages read into cache\" : 324,\n \"pages read into cache after truncate\" : 11,\n \"pages read into cache after truncate in prepare state\" : 0,\n \"pages read into cache requiring cache overflow entries\" : 0,\n \"pages read into cache requiring cache overflow for checkpoint\" : 0,\n \"pages read into cache skipping older cache overflow entries\" : 0,\n \"pages read into cache with skipped cache overflow entries needed later\" : 0,\n \"pages read into cache with skipped cache overflow entries needed later by checkpoint\" : 0,\n \"pages requested from the cache\" : 46897,\n \"pages seen by eviction walk\" : 0,\n \"pages selected for eviction unable to be evicted\" : 0,\n \"pages walked for eviction\" : 0,\n \"pages written from cache\" : 175,\n \"pages written requiring in-memory restoration\" : 0,\n \"percentage overhead\" : 8,\n \"tracked bytes belonging to internal pages in the cache\" : 40080,\n \"tracked bytes belonging to leaf pages in the cache\" : 773980,\n \"tracked dirty bytes in the cache\" : 0,\n \"tracked dirty pages in the cache\" : 0,\n \"unmodified pages evicted\" : 0\n },\n \"connection\" : {\n \"auto adjusting condition resets\" : 561,\n \"auto adjusting condition wait calls\" : 42647,\n \"detected system time went backwards\" : 0,\n \"files currently open\" : 170,\n \"memory allocations\" : 277416,\n \"memory frees\" : 266135,\n \"memory re-allocations\" : 23688,\n \"pthread mutex condition wait calls\" : 116127,\n \"pthread mutex shared lock read-lock calls\" : 140031,\n \"pthread mutex shared lock write-lock calls\" : 10159,\n \"total fsync I/Os\" : 760,\n \"total read I/Os\" : 2257,\n \"total write I/Os\" : 875\n },\n \"cursor\" : {\n \"cursor close calls that result in cache\" : 482,\n \"cursor create calls\" : 536,\n \"cursor insert calls\" : 296,\n \"cursor modify calls\" : 0,\n \"cursor next calls\" : 2968,\n \"cursor operation restarted\" : 0,\n \"cursor prev calls\" : 212,\n \"cursor remove calls\" : 9,\n \"cursor reserve calls\" : 0,\n \"cursor reset calls\" : 46322,\n \"cursor search calls\" : 27066,\n \"cursor search near calls\" : 441,\n \"cursor sweep buckets\" : 41532,\n \"cursor sweep cursors closed\" : 0,\n \"cursor sweep cursors examined\" : 13338,\n \"cursor sweeps\" : 6922,\n \"cursor update calls\" : 0,\n \"cursors currently cached\" : 170,\n \"cursors reused from cache\" : 312,\n \"truncate calls\" : 0\n },\n \"data-handle\" : {\n \"connection data handles currently active\" : 489,\n \"connection sweep candidate became referenced\" : 0,\n \"connection sweep dhandles closed\" : 0,\n \"connection sweep dhandles removed from hash list\" : 207,\n \"connection sweep time-of-death sets\" : 972,\n \"connection sweeps\" : 3469,\n \"session dhandles swept\" : 0,\n \"session sweep attempts\" : 373\n },\n \"lock\" : {\n \"checkpoint lock acquisitions\" : 437,\n \"checkpoint lock application thread wait time (usecs)\" : 0,\n \"checkpoint lock internal thread wait time (usecs)\" : 0,\n \"commit timestamp queue lock application thread time waiting (usecs)\" : 0,\n \"commit timestamp queue lock internal thread time waiting (usecs)\" : 0,\n \"commit timestamp queue read lock acquisitions\" : 0,\n \"commit timestamp queue write lock acquisitions\" : 0,\n \"dhandle lock application thread time waiting (usecs)\" : 0,\n \"dhandle lock internal thread time waiting (usecs)\" : 0,\n \"dhandle read lock acquisitions\" : 28619,\n \"dhandle write lock acquisitions\" : 909,\n \"metadata lock acquisitions\" : 116,\n \"metadata lock application thread wait time (usecs)\" : 0,\n \"metadata lock internal thread wait time (usecs)\" : 0,\n \"read timestamp queue lock application thread time waiting (usecs)\" : 0,\n \"read timestamp queue lock internal thread time waiting (usecs)\" : 0,\n \"read timestamp queue read lock acquisitions\" : 0,\n \"read timestamp queue write lock acquisitions\" : 0,\n \"schema lock acquisitions\" : 613,\n \"schema lock application thread wait time (usecs)\" : 0,\n \"schema lock internal thread wait time (usecs)\" : 0,\n \"table lock application thread time waiting for the table lock (usecs)\" : 0,\n \"table lock internal thread time waiting for the table lock (usecs)\" : 0,\n \"table read lock acquisitions\" : 0,\n \"table write lock acquisitions\" : 645,\n \"txn global lock application thread time waiting (usecs)\" : 0,\n \"txn global lock internal thread time waiting (usecs)\" : 0,\n \"txn global read lock acquisitions\" : 375,\n \"txn global write lock acquisitions\" : 354\n },\n \"log\" : {\n \"busy returns attempting to switch slots\" : 1,\n \"force archive time sleeping (usecs)\" : 0,\n \"log bytes of payload data\" : 49104,\n \"log bytes written\" : 105216,\n \"log files manually zero-filled\" : 0,\n \"log flush operations\" : 68872,\n \"log force write operations\" : 75951,\n \"log force write operations skipped\" : 75776,\n \"log records compressed\" : 36,\n \"log records not compressed\" : 23,\n \"log records too small to compress\" : 493,\n \"log release advances write LSN\" : 353,\n \"log scan operations\" : 4,\n \"log scan records requiring two reads\" : 3,\n \"log server thread advances write LSN\" : 175,\n \"log server thread write LSN walk skipped\" : 8776,\n \"log sync operations\" : 528,\n \"log sync time duration (usecs)\" : 29656979,\n \"log sync_dir operations\" : 1,\n \"log sync_dir time duration (usecs)\" : 0,\n \"log write operations\" : 552,\n \"logging bytes consolidated\" : 104704,\n \"maximum log file size\" : 104857600,\n \"number of pre-allocated log files to create\" : 2,\n \"pre-allocated log files not ready and missed\" : 1,\n \"pre-allocated log files prepared\" : 2,\n \"pre-allocated log files used\" : 0,\n \"records processed by log scan\" : 636,\n \"slot close lost race\" : 0,\n \"slot close unbuffered waits\" : 0,\n \"slot closures\" : 528,\n \"slot join atomic update races\" : 0,\n \"slot join calls atomic updates raced\" : 0,\n \"slot join calls did not yield\" : 552,\n \"slot join calls found active slot closed\" : 0,\n \"slot join calls slept\" : 0,\n \"slot join calls yielded\" : 0,\n \"slot join found active slot closed\" : 0,\n \"slot joins yield time (usecs)\" : 0,\n \"slot transitions unable to find free slot\" : 0,\n \"slot unbuffered writes\" : 0,\n \"total in-memory size of compressed records\" : 79123,\n \"total log buffer size\" : 33554432,\n \"total size of compressed records\" : 33250,\n \"written slots coalesced\" : 0,\n \"yields waiting for previous log file close\" : 0\n },\n \"perf\" : {\n \"file system read latency histogram (bucket 1) - 10-49ms\" : 5,\n \"file system read latency histogram (bucket 2) - 50-99ms\" : 0,\n \"file system read latency histogram (bucket 3) - 100-249ms\" : 0,\n \"file system read latency histogram (bucket 4) - 250-499ms\" : 0,\n \"file system read latency histogram (bucket 5) - 500-999ms\" : 0,\n \"file system read latency histogram (bucket 6) - 1000ms+\" : 0,\n \"file system write latency histogram (bucket 1) - 10-49ms\" : 9,\n \"file system write latency histogram (bucket 2) - 50-99ms\" : 0,\n \"file system write latency histogram (bucket 3) - 100-249ms\" : 0,\n \"file system write latency histogram (bucket 4) - 250-499ms\" : 0,\n \"file system write latency histogram (bucket 5) - 500-999ms\" : 0,\n \"file system write latency histogram (bucket 6) - 1000ms+\" : 0,\n \"operation read latency histogram (bucket 1) - 100-249us\" : 0,\n \"operation read latency histogram (bucket 2) - 250-499us\" : 0,\n \"operation read latency histogram (bucket 3) - 500-999us\" : 44,\n \"operation read latency histogram (bucket 4) - 1000-9999us\" : 20,\n \"operation read latency histogram (bucket 5) - 10000us+\" : 2,\n \"operation write latency histogram (bucket 1) - 100-249us\" : 0,\n \"operation write latency histogram (bucket 2) - 250-499us\" : 0,\n \"operation write latency histogram (bucket 3) - 500-999us\" : 7,\n \"operation write latency histogram (bucket 4) - 1000-9999us\" : 1,\n \"operation write latency histogram (bucket 5) - 10000us+\" : 1\n },\n \"reconciliation\" : {\n \"fast-path pages deleted\" : 0,\n \"page reconciliation calls\" : 193,\n \"page reconciliation calls for eviction\" : 1,\n \"pages deleted\" : 18,\n \"split bytes currently awaiting free\" : 0,\n \"split objects currently awaiting free\" : 0\n },\n \"session\" : {\n \"open cursor count\" : 22,\n \"open session count\" : 19,\n \"session query timestamp calls\" : 0,\n \"table alter failed calls\" : 0,\n \"table alter successful calls\" : 321,\n \"table alter unchanged and skipped\" : 963,\n \"table compact failed calls\" : 0,\n \"table compact successful calls\" : 0,\n \"table create failed calls\" : 0,\n \"table create successful calls\" : 7,\n \"table drop failed calls\" : 0,\n \"table drop successful calls\" : 0,\n \"table rebalance failed calls\" : 0,\n \"table rebalance successful calls\" : 0,\n \"table rename failed calls\" : 0,\n \"table rename successful calls\" : 0,\n \"table salvage failed calls\" : 0,\n \"table salvage successful calls\" : 0,\n \"table truncate failed calls\" : 0,\n \"table truncate successful calls\" : 0,\n \"table verify failed calls\" : 0,\n \"table verify successful calls\" : 0\n },\n \"thread-state\" : {\n \"active filesystem fsync calls\" : 0,\n \"active filesystem read calls\" : 0,\n \"active filesystem write calls\" : 0\n },\n \"thread-yield\" : {\n \"application thread time evicting (usecs)\" : 0,\n \"application thread time waiting for cache (usecs)\" : 0,\n \"connection close blocked waiting for transaction state stabilization\" : 0,\n \"connection close yielded for lsm manager shutdown\" : 0,\n \"data handle lock yielded\" : 0,\n \"get reference for page index and slot time sleeping (usecs)\" : 0,\n \"log server sync yielded for log write\" : 0,\n \"page access yielded due to prepare state change\" : 0,\n \"page acquire busy blocked\" : 0,\n \"page acquire eviction blocked\" : 0,\n \"page acquire locked blocked\" : 0,\n \"page acquire read blocked\" : 0,\n \"page acquire time sleeping (usecs)\" : 0,\n \"page delete rollback time sleeping for state change (usecs)\" : 0,\n \"page reconciliation yielded due to child modification\" : 0\n },\n \"transaction\" : {\n \"Number of prepared updates\" : 0,\n \"Number of prepared updates added to cache overflow\" : 0,\n \"Number of prepared updates resolved\" : 0,\n \"commit timestamp queue entries walked\" : 0,\n \"commit timestamp queue insert to empty\" : 0,\n \"commit timestamp queue inserts to head\" : 0,\n \"commit timestamp queue inserts total\" : 0,\n \"commit timestamp queue length\" : 0,\n \"number of named snapshots created\" : 0,\n \"number of named snapshots dropped\" : 0,\n \"prepared transactions\" : 0,\n \"prepared transactions committed\" : 0,\n \"prepared transactions currently active\" : 0,\n \"prepared transactions rolled back\" : 0,\n \"query timestamp calls\" : 1,\n \"read timestamp queue entries walked\" : 0,\n \"read timestamp queue insert to empty\" : 0,\n \"read timestamp queue inserts to head\" : 0,\n \"read timestamp queue inserts total\" : 0,\n \"read timestamp queue length\" : 0,\n \"rollback to stable calls\" : 0,\n \"rollback to stable updates aborted\" : 0,\n \"rollback to stable updates removed from cache overflow\" : 0,\n \"set timestamp calls\" : 0,\n \"set timestamp commit calls\" : 0,\n \"set timestamp commit updates\" : 0,\n \"set timestamp oldest calls\" : 0,\n \"set timestamp oldest updates\" : 0,\n \"set timestamp stable calls\" : 0,\n \"set timestamp stable updates\" : 0,\n \"transaction begins\" : 309,\n \"transaction checkpoint currently running\" : 0,\n \"transaction checkpoint generation\" : 117,\n \"transaction checkpoint max time (msecs)\" : 2264,\n \"transaction checkpoint min time (msecs)\" : 4,\n \"transaction checkpoint most recent time (msecs)\" : 43,\n \"transaction checkpoint scrub dirty target\" : 0,\n \"transaction checkpoint scrub time (msecs)\" : 0,\n \"transaction checkpoint total time (msecs)\" : 15771,\n \"transaction checkpoints\" : 116,\n \"transaction checkpoints skipped because database was clean\" : 0,\n \"transaction failures due to cache overflow\" : 0,\n \"transaction fsync calls for checkpoint after allocating the transaction ID\" : 116,\n \"transaction fsync duration for checkpoint after allocating the transaction ID (usecs)\" : 0,\n \"transaction range of IDs currently pinned\" : 0,\n \"transaction range of IDs currently pinned by a checkpoint\" : 0,\n \"transaction range of IDs currently pinned by named snapshots\" : 0,\n \"transaction range of timestamps currently pinned\" : 0,\n \"transaction range of timestamps pinned by a checkpoint\" : 0,\n \"transaction range of timestamps pinned by the oldest timestamp\" : 0,\n \"transaction sync calls\" : 0,\n \"transactions committed\" : 40,\n \"transactions rolled back\" : 269,\n \"update conflicts\" : 0\n },\n \"concurrentTransactions\" : {\n \"write\" : {\n \"out\" : 0,\n \"available\" : 128,\n \"totalTickets\" : 128\n },\n \"read\" : {\n \"out\" : 1,\n \"available\" : 127,\n \"totalTickets\" : 128\n }\n }\n}" } ]
Count the number of possible triangles | Practice | GeeksforGeeks
Given an unsorted array arr[] of n positive integers. Find the number of triangles that can be formed with three different array elements as lengths of three sides of triangles. Example 1: Input: n = 3 arr[] = {3, 5, 4} Output: 1 Explanation: A triangle is possible with all the elements 5, 3 and 4. Example 2: Input: n = 5 arr[] = {6, 4, 9, 7, 8} Output: 10 Explanation: There are 10 triangles possible with the given elements like (6,4,9), (6,7,8),... Your Task: This is a function problem. You only need to complete the function findNumberOfTriangles() that takes arr[] and n as input parameters and returns the count of total possible triangles. Expected Time Complexity: O(n2). Expected Space Complexity: O(1). Constraints: 3 <= n <= 103 1 <= arr[i] <= 103 0 shubham211019971 week ago simplest solution, T(n)=O(n^2) int pair(int arr[],int si,int ei,int x){ int i=si,j=ei,count=0; while(i<j){ int sum=arr[i]+arr[j]; if(sum>x){ count=count+(j-i); j--; }else{ i++; } } return count; } int findNumberOfTriangles(int arr[], int n){ sort(arr,arr+n); int count=0; for(int i=n-1;i>=2;i--){ count+=pair(arr,0,i-1,arr[i]); } return count; } 0 achaudhary1732 weeks ago class Solution{ //Function to count the number of possible triangles. static int findNumberOfTriangles(int arr[], int n) { Arrays.sort(arr); int count = 0; for(int i = arr.length - 1; i >= 0; i--){ int l = 0; int r = i - 1; while(l < r){ if(arr[l] + arr[r] > arr[i]){ count += (r - l); r--; } else{ l++; } } } return count; }} 0 wolfofsv2 weeks ago O(n^2) time and O(1) space int findNumberOfTriangles(int arr[], int n) { // code here sort(arr, arr + n); int ans = 0; for(int i = 0; i < n; i++){ int k = i + 2; for(int j = i + 1; j < n; j++){ while(k < n && arr[k] < arr[i] + arr[j]){ k++; } ans += k - (j + 1); } } return ans; } 0 ishubham0103 weeks ago C++ Solution: int count=0; sort(arr, arr+n); for(int i=0; i<(n-2); i++) { for(int j=i+1; j<(n-1); j++) { for(int k=j+1; k<n; k++) { if(arr[i]+arr[j]>arr[k]) count++; else break; } } } return count; -2 amrit_kumar1 month ago int findNumberOfTriangles(int arr[], int n) { sort(arr, arr+n); // sort the array in ascending order int count =0; // intialize reuslt to zero for(int i=n-1;i>=2;i--) // start from right end { int l =0; // left size is zero int r = i-1; // right side is i-1 while(l<r) { if(arr[l]+arr[r]>arr[i]) // if condition ssatisfied increase count { count+=r-l; // for a particular right side total count is calculated r--; // decrease the right value } else l++; // if condiiton failed increase the left side } } return count; } 0 asyrovPremium1 month ago public int CountTrianglesForSide(int[] arr, int side, int high) { int count = 0; for (int low = 0; low < high; high--) { while (low < high && arr[low] + arr[high] <= side) low++; count += high - low; } return count; } public int findNumberOfTriangles(int[] arr, int n) { int count = 0; Array.Sort(arr); for (int i = n - 1; i > 1; i--) count += CountTrianglesForSide(arr, side: arr[i], high: i - 1); return count; } -1 ashvinkict201 month ago // code here int ans =0; //We need to check only 1 condition a,b,c are sorted //a+b>c sort(arr,arr+n); // Fix c and try to find that satisfy the condition a+b>c // c+a>b,c+b>a is satisfied by default if a<b<c for(int c = n-1;c>=2;c--){ int a = 0; int b = c-1; while(b>a) { if(arr[a]+arr[b]>arr[c]){ ans += b-1; b--; }else{ a++; } } return ans; } 0 ashvinkict20 This comment was deleted. +2 abhijeet194031 month ago An optimised solution for C++ int findNumberOfTriangles(int arr[], int n) { // code here sort(arr,arr+n); int count = 0; for(int i=0;i<n-2;i++) { int c = 1; for(int j=i+2;j<n;j++) { if((arr[i]+arr[i+1])>arr[j]) count += c; else { for(int k=i+2;k<j;k++) { if(arr[i]+arr[k]>arr[j]) { count+=j-k; break; } } } c++; } } return count; } -2 aakasshuit2 months ago //Java Solution int count=0; Arrays.sort(arr); for(int i=0;i<n-2;i++){ for(int j=i+1;j<n-1;j++){ for(int k=j+1;k<n;k++){ if(arr[i]+arr[j]>arr[k]){ count++; } else{ break; } } } } return count; 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": 417, "s": 238, "text": "Given an unsorted array arr[] of n positive integers. Find the number of triangles that can be formed with three different array elements as lengths of three sides of triangles. " }, { "code": null, "e": 428, "s": 417, "text": "Example 1:" }, { "code": null, "e": 543, "s": 428, "text": "Input: \nn = 3\narr[] = {3, 5, 4}\nOutput: \n1\nExplanation: \nA triangle is possible \nwith all the elements 5, 3 and 4." }, { "code": null, "e": 554, "s": 543, "text": "Example 2:" }, { "code": null, "e": 702, "s": 554, "text": "Input: \nn = 5\narr[] = {6, 4, 9, 7, 8}\nOutput: \n10\nExplanation: \nThere are 10 triangles\npossible with the given elements like\n(6,4,9), (6,7,8),...\n" }, { "code": null, "e": 1015, "s": 704, "text": "Your Task: \nThis is a function problem. You only need to complete the function findNumberOfTriangles() that takes arr[] and n as input parameters and returns the count of total possible triangles.\n\nExpected Time Complexity: O(n2).\nExpected Space Complexity: O(1).\n\nConstraints:\n3 <= n <= 103\n1 <= arr[i] <= 103" }, { "code": null, "e": 1017, "s": 1015, "text": "0" }, { "code": null, "e": 1043, "s": 1017, "text": "shubham211019971 week ago" }, { "code": null, "e": 1074, "s": 1043, "text": "simplest solution, T(n)=O(n^2)" }, { "code": null, "e": 1505, "s": 1074, "text": "int pair(int arr[],int si,int ei,int x){\n int i=si,j=ei,count=0;\n while(i<j){\n int sum=arr[i]+arr[j];\n if(sum>x){\n count=count+(j-i);\n j--;\n }else{\n i++;\n }\n }\n return count;\n}\nint findNumberOfTriangles(int arr[], int n){\n sort(arr,arr+n);\n int count=0;\n for(int i=n-1;i>=2;i--){\n count+=pair(arr,0,i-1,arr[i]);\n }\n return count;\n }" }, { "code": null, "e": 1507, "s": 1505, "text": "0" }, { "code": null, "e": 1532, "s": 1507, "text": "achaudhary1732 weeks ago" }, { "code": null, "e": 2083, "s": 1532, "text": "class Solution{ //Function to count the number of possible triangles. static int findNumberOfTriangles(int arr[], int n) { Arrays.sort(arr); int count = 0; for(int i = arr.length - 1; i >= 0; i--){ int l = 0; int r = i - 1; while(l < r){ if(arr[l] + arr[r] > arr[i]){ count += (r - l); r--; } else{ l++; } } } return count; }}" }, { "code": null, "e": 2088, "s": 2086, "text": "0" }, { "code": null, "e": 2108, "s": 2088, "text": "wolfofsv2 weeks ago" }, { "code": null, "e": 2135, "s": 2108, "text": "O(n^2) time and O(1) space" }, { "code": null, "e": 2549, "s": 2135, "text": "int findNumberOfTriangles(int arr[], int n)\n {\n // code here\n sort(arr, arr + n);\n int ans = 0;\n for(int i = 0; i < n; i++){\n int k = i + 2;\n for(int j = i + 1; j < n; j++){\n while(k < n && arr[k] < arr[i] + arr[j]){\n k++;\n }\n ans += k - (j + 1);\n }\n }\n return ans;\n }" }, { "code": null, "e": 2551, "s": 2549, "text": "0" }, { "code": null, "e": 2574, "s": 2551, "text": "ishubham0103 weeks ago" }, { "code": null, "e": 2588, "s": 2574, "text": "C++ Solution:" }, { "code": null, "e": 2987, "s": 2588, "text": "\t\tint count=0;\n sort(arr, arr+n);\n for(int i=0; i<(n-2); i++)\n {\n for(int j=i+1; j<(n-1); j++)\n {\n for(int k=j+1; k<n; k++)\n {\n if(arr[i]+arr[j]>arr[k])\n count++;\n else \n break;\n }\n }\n }\n return count;" }, { "code": null, "e": 2990, "s": 2987, "text": "-2" }, { "code": null, "e": 3013, "s": 2990, "text": "amrit_kumar1 month ago" }, { "code": null, "e": 3773, "s": 3013, "text": " int findNumberOfTriangles(int arr[], int n)\n {\n sort(arr, arr+n); // sort the array in ascending order\n int count =0; // intialize reuslt to zero\n for(int i=n-1;i>=2;i--) // start from right end \n {\n int l =0; // left size is zero\n int r = i-1; // right side is i-1\n while(l<r)\n {\n if(arr[l]+arr[r]>arr[i]) // if condition ssatisfied increase count\n {\n count+=r-l; // for a particular right side total count is calculated\n r--; // decrease the right value\n }\n else\n l++; // if condiiton failed increase the left side\n }\n }\n return count;\n }" }, { "code": null, "e": 3775, "s": 3773, "text": "0" }, { "code": null, "e": 3800, "s": 3775, "text": "asyrovPremium1 month ago" }, { "code": null, "e": 4291, "s": 3800, "text": "public int CountTrianglesForSide(int[] arr, int side, int high)\n{\n int count = 0;\n \n for (int low = 0; low < high; high--)\n {\n while (low < high && arr[low] + arr[high] <= side) low++;\n count += high - low;\n }\n \n return count; \n}\npublic int findNumberOfTriangles(int[] arr, int n)\n{\n int count = 0;\n \n Array.Sort(arr);\n \n for (int i = n - 1; i > 1; i--)\n count += CountTrianglesForSide(arr, side: arr[i], high: i - 1);\n \n return count;\n}" }, { "code": null, "e": 4294, "s": 4291, "text": "-1" }, { "code": null, "e": 4318, "s": 4294, "text": "ashvinkict201 month ago" }, { "code": null, "e": 4673, "s": 4318, "text": "// code here int ans =0; //We need to check only 1 condition a,b,c are sorted //a+b>c sort(arr,arr+n); // Fix c and try to find that satisfy the condition a+b>c // c+a>b,c+b>a is satisfied by default if a<b<c for(int c = n-1;c>=2;c--){ int a = 0; int b = c-1; " }, { "code": null, "e": 4728, "s": 4673, "text": " while(b>a) { if(arr[a]+arr[b]>arr[c]){" }, { "code": null, "e": 4759, "s": 4728, "text": " ans += b-1;" }, { "code": null, "e": 4783, "s": 4759, "text": " b--;" }, { "code": null, "e": 4802, "s": 4783, "text": " }else{" }, { "code": null, "e": 4826, "s": 4802, "text": " a++;" }, { "code": null, "e": 4871, "s": 4826, "text": " } } return ans; }" }, { "code": null, "e": 4873, "s": 4871, "text": "0" }, { "code": null, "e": 4886, "s": 4873, "text": "ashvinkict20" }, { "code": null, "e": 4912, "s": 4886, "text": "This comment was deleted." }, { "code": null, "e": 4915, "s": 4912, "text": "+2" }, { "code": null, "e": 4940, "s": 4915, "text": "abhijeet194031 month ago" }, { "code": null, "e": 4970, "s": 4940, "text": "An optimised solution for C++" }, { "code": null, "e": 5616, "s": 4972, "text": "int findNumberOfTriangles(int arr[], int n) { // code here sort(arr,arr+n); int count = 0; for(int i=0;i<n-2;i++) { int c = 1; for(int j=i+2;j<n;j++) { if((arr[i]+arr[i+1])>arr[j]) count += c; else { for(int k=i+2;k<j;k++) { if(arr[i]+arr[k]>arr[j]) { count+=j-k; break; } } } c++; } } return count; }" }, { "code": null, "e": 5619, "s": 5616, "text": "-2" }, { "code": null, "e": 5642, "s": 5619, "text": "aakasshuit2 months ago" }, { "code": null, "e": 6060, "s": 5642, "text": "//Java Solution\n\n int count=0;\n Arrays.sort(arr);\n for(int i=0;i<n-2;i++){\n for(int j=i+1;j<n-1;j++){\n for(int k=j+1;k<n;k++){\n if(arr[i]+arr[j]>arr[k]){\n count++;\n }\n else{\n break;\n }\n }\n }\n }\n return count;" }, { "code": null, "e": 6206, "s": 6060, "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": 6242, "s": 6206, "text": " Login to access your submissions. " }, { "code": null, "e": 6252, "s": 6242, "text": "\nProblem\n" }, { "code": null, "e": 6262, "s": 6252, "text": "\nContest\n" }, { "code": null, "e": 6325, "s": 6262, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6473, "s": 6325, "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": 6681, "s": 6473, "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": 6787, "s": 6681, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to “read_csv” with Pandas. Use read_csv as a versatile tool | by Soner Yıldırım | Towards Data Science
The most time-consuming part of a data science project is data cleaning and preparation. Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of your project. We usually tend to use functions with default parameters which prevents us from taking full advantage of the function. One of the most widely used functions of Pandas is read_csv which reads comma-separated values (csv) files and creates a DataFrame. In this post, I will focus on many different parameters of read_csv function and how to efficiently use them. The basic data structure of Pandas is DataFrame which represents data in tabular form with labeled rows and columns. As always, we start with importing numpy and pandas. import numpy as npimport pandas as pd I created a sample DataFrame aiming to show the effect and usefulness of parameters so the values may not make sense. Let’s start with using read_csv with no optional parameters: df = pd.read_csv("SampleDataset.csv")df.head() The only required parameter is the file path. We need to tell pandas where the file is located. If the csv file is in the same working directory or folder, you can just write the name of the file. If not, we can specify the location as follows: df = pd.read_csv(r"C:\Users\soner\Downloads\SampleDataset.csv") An integer index starting from 0 is assigned to the DataFrame by default. We can explicitly define a column to be used as index. For example, we may want to use “ID” column as index: df = pd.read_csv("SampleDataset.csv", index_col='ID')df.head() It is a bit strange to have floating point ID numbers. I don’t think any company assigns ID numbers in this way. We can specify the data types of any column in read_csv function using dtype parameter: df = pd.read_csv("SampleDataset.csv", index_col='ID', dtype={'ID':np.int32})df.head() In some cases, depending on what we plan to do with date, we may not need all of the features (columns). We can drop the unnecessary columns after reading all data. However, a better option would be just reading the columns we need which can easily be done with usecols parameter: cols = ["ID","Deparment","Salary","StartDate","Location"]df = pd.read_csv("SampleDataset.csv", usecols=cols)df.head() We can also use indices of columns as argument to usecols parameter. Following code will do the job just fine: df = pd.read_csv("SampleDataset.csv", usecols=[2,3,4,5,6]) Let’s check the data types of columns: df = pd.read_csv("SampleDataset.csv")df.dtypesUnnamed: 0 int64RowNumber int64ID float64Deparment objectSalary int64StartDate objectLocation objectdtype: object The data type of StartDate column is object but we know this column includes dates so we can read the values as date by using parse_dates parameter. df = pd.read_csv("SampleDataset.csv", parse_dates=[5])df.dtypesUnnamed: 0 int64RowNumber int64ID float64Deparment objectSalary int64StartDate datetime64[ns]Location objectdtype: object The dates are now in a better suited format. Missing values are sometimes not in a format that can be detected as “missing” by Pandas. For example, in location column, ‘?’ is a missing value but there is no way read_csv function knows this unless we specify it. We can use na_values to indicate additional values to be recognized as “missing”: df = pd.read_csv("SampleDataset.csv", na_values=['?'])df.head() If we have a very large DataFrame and want to read only a part of it, we can use nrows parameter and indicate how many rows we want to read and put in the DataFrame: df = pd.read_csv("SampleDataset.csv")df.shape(30,7)df = pd.read_csv("SampleDataset.csv", nrows=10)df.shape(10,7) In some cases, we may want to skip some of the rows at the beginning of the file. We can just pass the number of rows to be skipped to skiprows paremeter or pass a list with integers indicating the lines to be skipped: skiprows=5 : Skip first 5 lines skiprows=[1,3] : Skip first line and third line Original DataFrame: df = pd.read_csv("SampleDataset.csv", skiprows=3)df.head() The first three rows skipped and the DataFrame starts from the 4th row. However, there is a problem in here. 4th row is used as column names. We can solve this issue using header parameter. In most cases, the first row in a csv file includes column names and inferred as header. Therefore, if no column names are specified, default behavior of csv file is to take header=0 and column names are inferred from the ,first line of the file. If header=None , column names are assigned as integer indices and first line of the file is read as first row of the DataFrame: df = pd.read_csv("SampleDataset.csv", header=None)df.head() So we can set header=None and use skiprows but keep in mind that the first line includes the column names. If skiprows=3, the first row of DataFrame becomes the person with ID=127. df = pd.read_csv("SampleDataset.csv", header=None, skiprows=3)df.head() If we want to change the name of columns or the file does not have a line to include columns names, we can use names parameter: cols=["Drop1","Drop2","Employee_ID","Department","Salary", "StartDate"]df = pd.read_csv("SampleDataset.csv", names=cols, skiprows=1)df.head() There are many additional parameters of read_csv function. I tried to explain the ones I commonly use but you can check the whole list of parameters here. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 505, "s": 172, "text": "The most time-consuming part of a data science project is data cleaning and preparation. Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of your project. We usually tend to use functions with default parameters which prevents us from taking full advantage of the function." }, { "code": null, "e": 747, "s": 505, "text": "One of the most widely used functions of Pandas is read_csv which reads comma-separated values (csv) files and creates a DataFrame. In this post, I will focus on many different parameters of read_csv function and how to efficiently use them." }, { "code": null, "e": 864, "s": 747, "text": "The basic data structure of Pandas is DataFrame which represents data in tabular form with labeled rows and columns." }, { "code": null, "e": 917, "s": 864, "text": "As always, we start with importing numpy and pandas." }, { "code": null, "e": 955, "s": 917, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 1073, "s": 955, "text": "I created a sample DataFrame aiming to show the effect and usefulness of parameters so the values may not make sense." }, { "code": null, "e": 1134, "s": 1073, "text": "Let’s start with using read_csv with no optional parameters:" }, { "code": null, "e": 1181, "s": 1134, "text": "df = pd.read_csv(\"SampleDataset.csv\")df.head()" }, { "code": null, "e": 1426, "s": 1181, "text": "The only required parameter is the file path. We need to tell pandas where the file is located. If the csv file is in the same working directory or folder, you can just write the name of the file. If not, we can specify the location as follows:" }, { "code": null, "e": 1490, "s": 1426, "text": "df = pd.read_csv(r\"C:\\Users\\soner\\Downloads\\SampleDataset.csv\")" }, { "code": null, "e": 1673, "s": 1490, "text": "An integer index starting from 0 is assigned to the DataFrame by default. We can explicitly define a column to be used as index. For example, we may want to use “ID” column as index:" }, { "code": null, "e": 1736, "s": 1673, "text": "df = pd.read_csv(\"SampleDataset.csv\", index_col='ID')df.head()" }, { "code": null, "e": 1937, "s": 1736, "text": "It is a bit strange to have floating point ID numbers. I don’t think any company assigns ID numbers in this way. We can specify the data types of any column in read_csv function using dtype parameter:" }, { "code": null, "e": 2041, "s": 1937, "text": "df = pd.read_csv(\"SampleDataset.csv\", index_col='ID', dtype={'ID':np.int32})df.head()" }, { "code": null, "e": 2322, "s": 2041, "text": "In some cases, depending on what we plan to do with date, we may not need all of the features (columns). We can drop the unnecessary columns after reading all data. However, a better option would be just reading the columns we need which can easily be done with usecols parameter:" }, { "code": null, "e": 2440, "s": 2322, "text": "cols = [\"ID\",\"Deparment\",\"Salary\",\"StartDate\",\"Location\"]df = pd.read_csv(\"SampleDataset.csv\", usecols=cols)df.head()" }, { "code": null, "e": 2551, "s": 2440, "text": "We can also use indices of columns as argument to usecols parameter. Following code will do the job just fine:" }, { "code": null, "e": 2610, "s": 2551, "text": "df = pd.read_csv(\"SampleDataset.csv\", usecols=[2,3,4,5,6])" }, { "code": null, "e": 2649, "s": 2610, "text": "Let’s check the data types of columns:" }, { "code": null, "e": 2856, "s": 2649, "text": "df = pd.read_csv(\"SampleDataset.csv\")df.dtypesUnnamed: 0 int64RowNumber int64ID float64Deparment objectSalary int64StartDate objectLocation objectdtype: object" }, { "code": null, "e": 3005, "s": 2856, "text": "The data type of StartDate column is object but we know this column includes dates so we can read the values as date by using parse_dates parameter." }, { "code": null, "e": 3278, "s": 3005, "text": "df = pd.read_csv(\"SampleDataset.csv\", parse_dates=[5])df.dtypesUnnamed: 0 int64RowNumber int64ID float64Deparment objectSalary int64StartDate datetime64[ns]Location objectdtype: object" }, { "code": null, "e": 3323, "s": 3278, "text": "The dates are now in a better suited format." }, { "code": null, "e": 3622, "s": 3323, "text": "Missing values are sometimes not in a format that can be detected as “missing” by Pandas. For example, in location column, ‘?’ is a missing value but there is no way read_csv function knows this unless we specify it. We can use na_values to indicate additional values to be recognized as “missing”:" }, { "code": null, "e": 3686, "s": 3622, "text": "df = pd.read_csv(\"SampleDataset.csv\", na_values=['?'])df.head()" }, { "code": null, "e": 3852, "s": 3686, "text": "If we have a very large DataFrame and want to read only a part of it, we can use nrows parameter and indicate how many rows we want to read and put in the DataFrame:" }, { "code": null, "e": 3965, "s": 3852, "text": "df = pd.read_csv(\"SampleDataset.csv\")df.shape(30,7)df = pd.read_csv(\"SampleDataset.csv\", nrows=10)df.shape(10,7)" }, { "code": null, "e": 4184, "s": 3965, "text": "In some cases, we may want to skip some of the rows at the beginning of the file. We can just pass the number of rows to be skipped to skiprows paremeter or pass a list with integers indicating the lines to be skipped:" }, { "code": null, "e": 4216, "s": 4184, "text": "skiprows=5 : Skip first 5 lines" }, { "code": null, "e": 4264, "s": 4216, "text": "skiprows=[1,3] : Skip first line and third line" }, { "code": null, "e": 4284, "s": 4264, "text": "Original DataFrame:" }, { "code": null, "e": 4343, "s": 4284, "text": "df = pd.read_csv(\"SampleDataset.csv\", skiprows=3)df.head()" }, { "code": null, "e": 4485, "s": 4343, "text": "The first three rows skipped and the DataFrame starts from the 4th row. However, there is a problem in here. 4th row is used as column names." }, { "code": null, "e": 4780, "s": 4485, "text": "We can solve this issue using header parameter. In most cases, the first row in a csv file includes column names and inferred as header. Therefore, if no column names are specified, default behavior of csv file is to take header=0 and column names are inferred from the ,first line of the file." }, { "code": null, "e": 4908, "s": 4780, "text": "If header=None , column names are assigned as integer indices and first line of the file is read as first row of the DataFrame:" }, { "code": null, "e": 4968, "s": 4908, "text": "df = pd.read_csv(\"SampleDataset.csv\", header=None)df.head()" }, { "code": null, "e": 5149, "s": 4968, "text": "So we can set header=None and use skiprows but keep in mind that the first line includes the column names. If skiprows=3, the first row of DataFrame becomes the person with ID=127." }, { "code": null, "e": 5221, "s": 5149, "text": "df = pd.read_csv(\"SampleDataset.csv\", header=None, skiprows=3)df.head()" }, { "code": null, "e": 5349, "s": 5221, "text": "If we want to change the name of columns or the file does not have a line to include columns names, we can use names parameter:" }, { "code": null, "e": 5491, "s": 5349, "text": "cols=[\"Drop1\",\"Drop2\",\"Employee_ID\",\"Department\",\"Salary\", \"StartDate\"]df = pd.read_csv(\"SampleDataset.csv\", names=cols, skiprows=1)df.head()" }, { "code": null, "e": 5646, "s": 5491, "text": "There are many additional parameters of read_csv function. I tried to explain the ones I commonly use but you can check the whole list of parameters here." } ]
SHA in Python
In this tutorial, we are going to learn about the hashlib module that gives us different SHA. (Secure Hash Algorithms) is set of cryptographic hash functions. Let's install the module by typing the following command. pip install hashlib We can see the available algorithms in the hashlib module using algorithms_guaranteed set. Let's see them by running the following code. Live Demo # importing the hashlib module import hashlib # printing available algorithms print(hashlib.algorithms_guaranteed) If you run the above code, then you will get the following result. {'sha256', 'sha512', 'sha224', 'shake_256', 'blake2s', 'shake_128', 'sha384', 'sha3_384', 'sha3_512', 'sha3_224', 'md5', 'sha3_256', 'sha1', 'blake2b'} Let's see an example on how to user sha256 algorithm. Live Demo # importing the hashlib module import hashlib # initialinzing a string # the string will be hashed using the 'sha256' name = 'Tutorialspoint' # convert the string to bytes using 'encode' # hash functions only accepts encoded strings encoded_name = name.encode() # Now, pass the encoded_name to the **sha256** function hashed_name = hashlib.sha256(encoded_name) # we have hashed object # we can't understand it # print the hexadecimal version using 'hexdigest()' method print("Object:", hashed_name) print("Hexadecimal format:", hashed_name.hexdigest()) If you run the above code, then you will get the following result. Object: <sha256 HASH object @ 0x000002A416E1BAE0> Hexadecimal format: 447c2329228a452aa77102dc7d4eca0ee4c6d52a17e9c17408f8917e51e 3 You can use the remaining algorithms similar to the sha256. If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1221, "s": 1062, "text": "In this tutorial, we are going to learn about the hashlib module that gives us different SHA.\n(Secure Hash Algorithms) is set of cryptographic hash functions." }, { "code": null, "e": 1279, "s": 1221, "text": "Let's install the module by typing the following command." }, { "code": null, "e": 1299, "s": 1279, "text": "pip install hashlib" }, { "code": null, "e": 1436, "s": 1299, "text": "We can see the available algorithms in the hashlib module using algorithms_guaranteed set. Let's see them by running the following code." }, { "code": null, "e": 1447, "s": 1436, "text": " Live Demo" }, { "code": null, "e": 1562, "s": 1447, "text": "# importing the hashlib module\nimport hashlib\n# printing available algorithms\nprint(hashlib.algorithms_guaranteed)" }, { "code": null, "e": 1629, "s": 1562, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 1781, "s": 1629, "text": "{'sha256', 'sha512', 'sha224', 'shake_256', 'blake2s', 'shake_128', 'sha384', 'sha3_384', 'sha3_512', 'sha3_224', 'md5', 'sha3_256', 'sha1', 'blake2b'}" }, { "code": null, "e": 1835, "s": 1781, "text": "Let's see an example on how to user sha256 algorithm." }, { "code": null, "e": 1846, "s": 1835, "text": " Live Demo" }, { "code": null, "e": 2399, "s": 1846, "text": "# importing the hashlib module\nimport hashlib\n# initialinzing a string\n# the string will be hashed using the 'sha256'\nname = 'Tutorialspoint'\n# convert the string to bytes using 'encode'\n# hash functions only accepts encoded strings\nencoded_name = name.encode()\n# Now, pass the encoded_name to the **sha256** function\nhashed_name = hashlib.sha256(encoded_name)\n# we have hashed object\n# we can't understand it\n# print the hexadecimal version using 'hexdigest()' method\nprint(\"Object:\", hashed_name)\nprint(\"Hexadecimal format:\", hashed_name.hexdigest())" }, { "code": null, "e": 2466, "s": 2399, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2598, "s": 2466, "text": "Object: <sha256 HASH object @ 0x000002A416E1BAE0>\nHexadecimal format: 447c2329228a452aa77102dc7d4eca0ee4c6d52a17e9c17408f8917e51e\n3" }, { "code": null, "e": 2736, "s": 2598, "text": "You can use the remaining algorithms similar to the sha256. If you have any queries in the\ntutorial, mention them in the comment section." } ]
How to shade the regions between the curves in Matplotlib?
To shade the regions between curves, we can use the fill_between() method. Initialize the variable n. Initiliize x and y data points using numpy. Initialize the variable n. Initiliize x and y data points using numpy. Create a figure and a set of subplots, fig and ax. Create a figure and a set of subplots, fig and ax. Plot the curve using plot method. Plot the curve using plot method. Use fill_between() method, fill the area between the two curves. Use fill_between() method, fill the area between the two curves. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True n = 256 X = np.linspace(-np.pi, np.pi, n, endpoint=True) Y = np.sin(2 * X) fig, ax = plt.subplots() ax.plot(X, Y, color='blue', alpha=1.0) ax.fill_between(X, 0, Y, color='blue', alpha=.2) plt.show()
[ { "code": null, "e": 1137, "s": 1062, "text": "To shade the regions between curves, we can use the fill_between() method." }, { "code": null, "e": 1208, "s": 1137, "text": "Initialize the variable n. Initiliize x and y data points using numpy." }, { "code": null, "e": 1279, "s": 1208, "text": "Initialize the variable n. Initiliize x and y data points using numpy." }, { "code": null, "e": 1330, "s": 1279, "text": "Create a figure and a set of subplots, fig and ax." }, { "code": null, "e": 1381, "s": 1330, "text": "Create a figure and a set of subplots, fig and ax." }, { "code": null, "e": 1415, "s": 1381, "text": "Plot the curve using plot method." }, { "code": null, "e": 1449, "s": 1415, "text": "Plot the curve using plot method." }, { "code": null, "e": 1514, "s": 1449, "text": "Use fill_between() method, fill the area between the two curves." }, { "code": null, "e": 1579, "s": 1514, "text": "Use fill_between() method, fill the area between the two curves." }, { "code": null, "e": 1621, "s": 1579, "text": "To display the figure, use show() method." }, { "code": null, "e": 1663, "s": 1621, "text": "To display the figure, use show() method." }, { "code": null, "e": 2000, "s": 1663, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nn = 256\nX = np.linspace(-np.pi, np.pi, n, endpoint=True)\nY = np.sin(2 * X)\nfig, ax = plt.subplots()\nax.plot(X, Y, color='blue', alpha=1.0)\nax.fill_between(X, 0, Y, color='blue', alpha=.2)\nplt.show()" } ]
'abstract' keyword in Java
'abstract' keyword is used to declare the method or a class as abstract. A class which contains the abstract keyword in its declaration is known as an abstract class. Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); ) Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); ) But, if a class has at least one abstract method, then the class must be declared abstract. But, if a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it. To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it. This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration. /* File name : Employee.java */ public abstract class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } You can observe that except abstract methods the Employee class is the same as the normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now you can try to instantiate the Employee class in the following way − /* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } } When you compile the above class, it gives you the following error − Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract. The abstract keyword is used to declare the method as abstract. The abstract keyword is used to declare the method as abstract. You have to place the abstract keyword before the method name in the method declaration. You have to place the abstract keyword before the method name in the method declaration. An abstract method contains a method signature, but no method body. An abstract method contains a method signature, but no method body. Instead of curly braces, an abstract method will have a semicolon (;) at the end. Instead of curly braces, an abstract method will have a semicolon (;) at the end. Following is an example of the abstract method. public abstract class Employee { private String name; private String address; private int number; public abstract double computePay(); // Remainder of class definition } Declaring a method as abstract has two consequences − The class containing it must be declared as abstract. The class containing it must be declared as abstract. Any class inheriting the current class must either override the abstract method or declare itself as abstract. Any class inheriting the current class must either override the abstract method or declare itself as abstract. Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated. Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below − /* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } // Remainder of class definition }
[ { "code": null, "e": 1135, "s": 1062, "text": "'abstract' keyword is used to declare the method or a class as abstract." }, { "code": null, "e": 1229, "s": 1135, "text": "A class which contains the abstract keyword in its declaration is known as an abstract class." }, { "code": null, "e": 1339, "s": 1229, "text": "Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )" }, { "code": null, "e": 1449, "s": 1339, "text": "Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )" }, { "code": null, "e": 1541, "s": 1449, "text": "But, if a class has at least one abstract method, then the class must be declared abstract." }, { "code": null, "e": 1633, "s": 1541, "text": "But, if a class has at least one abstract method, then the class must be declared abstract." }, { "code": null, "e": 1693, "s": 1633, "text": "If a class is declared abstract, it cannot be instantiated." }, { "code": null, "e": 1753, "s": 1693, "text": "If a class is declared abstract, it cannot be instantiated." }, { "code": null, "e": 1878, "s": 1753, "text": "To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it." }, { "code": null, "e": 2003, "s": 1878, "text": "To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it." }, { "code": null, "e": 2108, "s": 2003, "text": "If you inherit an abstract class, you have to provide implementations to all the abstract methods in it." }, { "code": null, "e": 2213, "s": 2108, "text": "If you inherit an abstract class, you have to provide implementations to all the abstract methods in it." }, { "code": null, "e": 2384, "s": 2213, "text": "This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration." }, { "code": null, "e": 3287, "s": 2384, "text": "/* File name : Employee.java */\npublic abstract class Employee {\n private String name;\n private String address;\n private int number;\n\n public Employee(String name, String address, int number) {\n System.out.println(\"Constructing an Employee\");\n this.name = name;\n this.address = address;\n this.number = number;\n }\n public double computePay() {\n System.out.println(\"Inside Employee computePay\");\n return 0.0;\n }\n public void mailCheck() {\n System.out.println(\"Mailing a check to \" + this.name + \" \" + this.address);\n }\n public String toString() {\n return name + \" \" + address + \" \" + number;\n }\n public String getName() {\n return name;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String newAddress) {\n address = newAddress;\n }\n public int getNumber() {\n return number;\n }\n}" }, { "code": null, "e": 3486, "s": 3287, "text": "You can observe that except abstract methods the Employee class is the same as the normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor." }, { "code": null, "e": 3559, "s": 3486, "text": "Now you can try to instantiate the Employee class in the following way −" }, { "code": null, "e": 3895, "s": 3559, "text": "/* File name : AbstractDemo.java */\npublic class AbstractDemo {\n\n public static void main(String [] args) {\n /* Following is not allowed and would raise error */\n Employee e = new Employee(\"George W.\", \"Houston, TX\", 43);\n System.out.println(\"\\n Call mailCheck using Employee reference--\");\n e.mailCheck();\n }\n}" }, { "code": null, "e": 3964, "s": 3895, "text": "When you compile the above class, it gives you the following error −" }, { "code": null, "e": 4125, "s": 3964, "text": "Employee.java:46: Employee is abstract; cannot be instantiated\n Employee e = new Employee(\"George W.\", \"Houston, TX\", 43); \n ^\n1 error" }, { "code": null, "e": 4328, "s": 4125, "text": "If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract." }, { "code": null, "e": 4392, "s": 4328, "text": "The abstract keyword is used to declare the method as abstract." }, { "code": null, "e": 4456, "s": 4392, "text": "The abstract keyword is used to declare the method as abstract." }, { "code": null, "e": 4545, "s": 4456, "text": "You have to place the abstract keyword before the method name in the method declaration." }, { "code": null, "e": 4634, "s": 4545, "text": "You have to place the abstract keyword before the method name in the method declaration." }, { "code": null, "e": 4702, "s": 4634, "text": "An abstract method contains a method signature, but no method body." }, { "code": null, "e": 4770, "s": 4702, "text": "An abstract method contains a method signature, but no method body." }, { "code": null, "e": 4852, "s": 4770, "text": "Instead of curly braces, an abstract method will have a semicolon (;) at the end." }, { "code": null, "e": 4934, "s": 4852, "text": "Instead of curly braces, an abstract method will have a semicolon (;) at the end." }, { "code": null, "e": 4982, "s": 4934, "text": "Following is an example of the abstract method." }, { "code": null, "e": 5168, "s": 4982, "text": "public abstract class Employee {\n private String name;\n private String address;\n private int number;\n\n public abstract double computePay();\n // Remainder of class definition\n}" }, { "code": null, "e": 5222, "s": 5168, "text": "Declaring a method as abstract has two consequences −" }, { "code": null, "e": 5276, "s": 5222, "text": "The class containing it must be declared as abstract." }, { "code": null, "e": 5330, "s": 5276, "text": "The class containing it must be declared as abstract." }, { "code": null, "e": 5441, "s": 5330, "text": "Any class inheriting the current class must either override the abstract method or declare itself as abstract." }, { "code": null, "e": 5552, "s": 5441, "text": "Any class inheriting the current class must either override the abstract method or declare itself as abstract." }, { "code": null, "e": 5715, "s": 5552, "text": "Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated." }, { "code": null, "e": 5831, "s": 5715, "text": "Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below −" }, { "code": null, "e": 6112, "s": 5831, "text": "/* File name : Salary.java */\npublic class Salary extends Employee {\n private double salary; // Annual salary\n\n public double computePay() {\n System.out.println(\"Computing salary pay for \" + getName());\n return salary/52;\n }\n // Remainder of class definition\n}" } ]
How to enable / Disable Enhanced Protection Mode in Internet Explorer using PowerShell?
Internet Explorer (IE) supports the enhanced protection mode for more security of the browser and the same can be enabled/disabled using PowerShell. Let see when we can find this setting in IE. Internet Explorer → Internet Options → Advanced → Enable Enhanced Protection Mode We can modify this setting using PowerShell and for that registry settings need to be done. Registry value can be found under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main and the key name is Isolation for enhanced protection mode. PMIL – To disable IE enhanced protection Mode PMIL – To disable IE enhanced protection Mode PMEM – To Enable IE enhanced protection mode PMEM – To Enable IE enhanced protection mode To make the changes using the script. If there is no Isolation Key exists you can use the below command to create a new key and value. New-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' ` -Name Isolation -Value "PMEM" -ErrorAction Ignore -Verbose If the Isolation key already exists then you just need to set the registry value. For example, Set-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' ` -Name Isolation -Value "PMEM" -ErrorAction Ignore -Verbose If there is no Isolation Key exists you can use the below command to create a new key and value. New-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' ` -Name Isolation -Value "PMIL" -ErrorAction Ignore -Verbose If the Isolation key already exists then you just need to set the registry value. For example, Set-ItemProperty 'HKCU:\SOFTWARE\Microsoft\Internet Explorer\Main' ` -Name Isolation -Value "PMIL" -ErrorAction Ignore -Verbose
[ { "code": null, "e": 1256, "s": 1062, "text": "Internet Explorer (IE) supports the enhanced protection mode for more security of the browser and the same can be enabled/disabled using PowerShell. Let see when we can find this setting in IE." }, { "code": null, "e": 1338, "s": 1256, "text": "Internet Explorer → Internet Options → Advanced → Enable Enhanced Protection Mode" }, { "code": null, "e": 1594, "s": 1338, "text": "We can modify this setting using PowerShell and for that registry settings need to be done. Registry value can be found under Computer\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Internet Explorer\\Main and the key name is Isolation for enhanced protection mode." }, { "code": null, "e": 1640, "s": 1594, "text": "PMIL – To disable IE enhanced protection Mode" }, { "code": null, "e": 1686, "s": 1640, "text": "PMIL – To disable IE enhanced protection Mode" }, { "code": null, "e": 1731, "s": 1686, "text": "PMEM – To Enable IE enhanced protection mode" }, { "code": null, "e": 1776, "s": 1731, "text": "PMEM – To Enable IE enhanced protection mode" }, { "code": null, "e": 1814, "s": 1776, "text": "To make the changes using the script." }, { "code": null, "e": 1911, "s": 1814, "text": "If there is no Isolation Key exists you can use the below command to create a new key and value." }, { "code": null, "e": 2042, "s": 1911, "text": "New-ItemProperty 'HKCU:\\SOFTWARE\\Microsoft\\Internet Explorer\\Main' `\n -Name Isolation -Value \"PMEM\" -ErrorAction Ignore -Verbose" }, { "code": null, "e": 2137, "s": 2042, "text": "If the Isolation key already exists then you just need to set the registry value. For example," }, { "code": null, "e": 2268, "s": 2137, "text": "Set-ItemProperty 'HKCU:\\SOFTWARE\\Microsoft\\Internet Explorer\\Main' `\n -Name Isolation -Value \"PMEM\" -ErrorAction Ignore -Verbose" }, { "code": null, "e": 2365, "s": 2268, "text": "If there is no Isolation Key exists you can use the below command to create a new key and value." }, { "code": null, "e": 2496, "s": 2365, "text": "New-ItemProperty 'HKCU:\\SOFTWARE\\Microsoft\\Internet Explorer\\Main' `\n -Name Isolation -Value \"PMIL\" -ErrorAction Ignore -Verbose" }, { "code": null, "e": 2591, "s": 2496, "text": "If the Isolation key already exists then you just need to set the registry value. For example," }, { "code": null, "e": 2722, "s": 2591, "text": "Set-ItemProperty 'HKCU:\\SOFTWARE\\Microsoft\\Internet Explorer\\Main' `\n -Name Isolation -Value \"PMIL\" -ErrorAction Ignore -Verbose" } ]
Import Modules From Another Folder in Python - GeeksforGeeks
17 Jun, 2021 In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two ways: Using sys.path Using PythonPath. Create a module for demonstration: File name: module0.py Python3 def run(): print("Module 0 imported successfully") sys.path: It is a built-in variable within the python sys module. It contains a list of directories that the interpreter will search in for the required modules. Python3 import sys # Prints the list of directories that the # interpreter will search for the required module. print(sys.path) Output: In this approach, Insert or Append the path of the directory containing the modules in sys.path. Syntax: sys.path.insert(0, path) sys.path.append(path) Example: Suppose we need to import the following modules from “Desktop\\Task\\modules” in “Desktop\\VScode\\Projects\\ImportModule\\main.py”. Insert/Append the path to sys.path and import module0 present in the directory and call its run function. Python3 import sys # Insert the path of modules folder sys.path.insert(0, "C:\\Users\\anila\\Desktop\\Task\\modules") # Import the module0 directly since # the current path is of modules.import module0 # Prints "Module0 imported successfully"module0.run() Output: PYTHONPATH : It is an environment variable which you can set to add additional directories where python will look for modules and packages. Open a terminal or command prompt and enter the following command: Syntax: set PYTHONPATH=path_to_module_folder Add the path to PYTHONPATH and import module0 present in the directory and call its run function. Below is the implementation: Python3 # Import the module0 directly since # the current path is of modules.import module0 # Prints "Module0 imported successfully"module0.run() Output: Picked 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25815, "s": 25537, "text": "In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder." }, { "code": null, "e": 25843, "s": 25815, "text": "It can be done in two ways:" }, { "code": null, "e": 25858, "s": 25843, "text": "Using sys.path" }, { "code": null, "e": 25876, "s": 25858, "text": "Using PythonPath." }, { "code": null, "e": 25911, "s": 25876, "text": "Create a module for demonstration:" }, { "code": null, "e": 25933, "s": 25911, "text": "File name: module0.py" }, { "code": null, "e": 25941, "s": 25933, "text": "Python3" }, { "code": "def run(): print(\"Module 0 imported successfully\")", "e": 25995, "s": 25941, "text": null }, { "code": null, "e": 26157, "s": 25995, "text": "sys.path: It is a built-in variable within the python sys module. It contains a list of directories that the interpreter will search in for the required modules." }, { "code": null, "e": 26165, "s": 26157, "text": "Python3" }, { "code": "import sys # Prints the list of directories that the # interpreter will search for the required module. print(sys.path)", "e": 26286, "s": 26165, "text": null }, { "code": null, "e": 26294, "s": 26286, "text": "Output:" }, { "code": null, "e": 26391, "s": 26294, "text": "In this approach, Insert or Append the path of the directory containing the modules in sys.path." }, { "code": null, "e": 26399, "s": 26391, "text": "Syntax:" }, { "code": null, "e": 26424, "s": 26399, "text": "sys.path.insert(0, path)" }, { "code": null, "e": 26446, "s": 26424, "text": "sys.path.append(path)" }, { "code": null, "e": 26588, "s": 26446, "text": "Example: Suppose we need to import the following modules from “Desktop\\\\Task\\\\modules” in “Desktop\\\\VScode\\\\Projects\\\\ImportModule\\\\main.py”." }, { "code": null, "e": 26694, "s": 26588, "text": "Insert/Append the path to sys.path and import module0 present in the directory and call its run function." }, { "code": null, "e": 26702, "s": 26694, "text": "Python3" }, { "code": "import sys # Insert the path of modules folder sys.path.insert(0, \"C:\\\\Users\\\\anila\\\\Desktop\\\\Task\\\\modules\") # Import the module0 directly since # the current path is of modules.import module0 # Prints \"Module0 imported successfully\"module0.run()", "e": 26953, "s": 26702, "text": null }, { "code": null, "e": 26961, "s": 26953, "text": "Output:" }, { "code": null, "e": 27101, "s": 26961, "text": "PYTHONPATH : It is an environment variable which you can set to add additional directories where python will look for modules and packages." }, { "code": null, "e": 27168, "s": 27101, "text": "Open a terminal or command prompt and enter the following command:" }, { "code": null, "e": 27213, "s": 27168, "text": "Syntax: set PYTHONPATH=path_to_module_folder" }, { "code": null, "e": 27311, "s": 27213, "text": "Add the path to PYTHONPATH and import module0 present in the directory and call its run function." }, { "code": null, "e": 27340, "s": 27311, "text": "Below is the implementation:" }, { "code": null, "e": 27348, "s": 27340, "text": "Python3" }, { "code": "# Import the module0 directly since # the current path is of modules.import module0 # Prints \"Module0 imported successfully\"module0.run()", "e": 27487, "s": 27348, "text": null }, { "code": null, "e": 27495, "s": 27487, "text": "Output:" }, { "code": null, "e": 27502, "s": 27495, "text": "Picked" }, { "code": null, "e": 27517, "s": 27502, "text": "python-modules" }, { "code": null, "e": 27524, "s": 27517, "text": "Python" }, { "code": null, "e": 27622, "s": 27524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27654, "s": 27622, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27696, "s": 27654, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27738, "s": 27696, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27765, "s": 27738, "text": "Python Classes and Objects" }, { "code": null, "e": 27821, "s": 27765, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27843, "s": 27821, "text": "Defaultdict in Python" }, { "code": null, "e": 27882, "s": 27843, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27913, "s": 27882, "text": "Python | os.path.join() method" }, { "code": null, "e": 27942, "s": 27913, "text": "Create a directory in Python" } ]
Find all divisors of a natural number | Set 2 - GeeksforGeeks
11 Jan, 2022 Given a natural number n, print all distinct divisors of it. Examples: Input : n = 10 Output: 1 2 5 10 Input: n = 100 Output: 1 2 4 5 10 20 25 50 100 Input: n = 125 Output: 1 5 25 125 We strongly recommend referring to the below article as a prerequisite. Find all divisors of a natural number | Set 1In the above post, we had found a way to find all the divisors in O(sqrt(n)).However there is still a minor problem in the solution, can you guess? Yes! the output is not in a sorted fashion which we had got using brute-force technique. How to print the output in sorted order? If we observe the output which we had got, we can analyze that the divisors are printed in a zig-zag fashion (small, large pairs). Hence if we store half of them then we can print them in sorted order. Below is an implementation for the same: C++ Java Python3 C# PHP Javascript // A O(sqrt(n)) program that prints all divisors// in sorted order#include <bits/stdc++.h>using namespace std; // function to print the divisorsvoid printDivisors(int n){ // Vector to store half of the divisors vector<int> v; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) printf("%d ", i); else { printf("%d ", i); // push the second divisor in the vector v.push_back(n / i); } } } // The vector will be printed in reverse for (int i = v.size() - 1; i >= 0; i--) printf("%d ", v[i]);} /* Driver program to test above function */int main(){ printf("The divisors of 100 are: \n"); printDivisors(100); return 0;} // A O(sqrt(n)) java program that prints all divisors// in sorted order import java.util.Vector; class Test { // method to print the divisors static void printDivisors(int n) { // Vector to store half of the divisors Vector<Integer> v = new Vector<>(); for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) System.out.printf("%d ", i); else { System.out.printf("%d ", i); // push the second divisor in the vector v.add(n / i); } } } // The vector will be printed in reverse for (int i = v.size() - 1; i >= 0; i--) System.out.printf("%d ", v.get(i)); } // Driver method public static void main(String args[]) { System.out.println("The divisors of 100 are: "); printDivisors(100); }} # A O(sqrt(n)) java program that prints# all divisors in sorted orderimport math # Method to print the divisorsdef printDivisors(n) : list = [] # List to store half of the divisors for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : # Check if divisors are equal if (n / i == i) : print (i, end =" ") else : # Otherwise print both print (i, end =" ") list.append(int(n / i)) # The list will be printed in reverse for i in list[::-1] : print (i, end =" ") # Driver methodprint ("The divisors of 100 are: ")printDivisors(100) # This code is contributed by Gitanjali // A O(sqrt(n)) C# program that// prints all divisors in sorted orderusing System; class GFG { // method to print the divisors static void printDivisors(int n) { // Vector to store half // of the divisors int[] v = new int[n]; int t = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) Console.Write(i + " "); else { Console.Write(i + " "); // push the second divisor // in the vector v[t++] = n / i; } } } // The vector will be // printed in reverse for (int i = t - 1; i >= 0; i--) Console.Write(v[i] + " "); } // Driver Code public static void Main() { Console.Write("The divisors of 100 are: \n"); printDivisors(100); }} // This code is contributed// by ChitraNayal <?php// A O(sqrt(n)) program that// prints all divisors in// sorted order // function to print// the divisorsfunction printDivisors($n){ // Vector to store half // of the divisors $v; $t = 0; for ($i = 1; $i <= (int)sqrt($n); $i++) { if ($n % $i == 0) { // check if divisors are equal if ((int)$n / $i == $i) echo $i . " "; else { echo $i . " "; // push the second // divisor in the vector $v[$t++] = (int)$n / $i; } } } // The vector will be // printed in reverse for ($i = count($v) - 1; $i >= 0; $i--) echo $v[$i] . " ";} // Driver codeecho "The divisors of 100 are: \n";printDivisors(100); // This code is contributed by mits?> <script> // A O(sqrt(n)) program that// prints all divisors in// sorted order // function to print// the divisorsfunction printDivisors(n){ // Vector to store half // of the divisors let v = []; let t = 0; for (let i = 1; i <= parseInt(Math.sqrt(n)); i++) { if (n % i == 0) { // check if divisors are equal if (parseInt(n / i) == i) document.write(i + " "); else { document.write(i + " "); // push the second // divisor in the vector v[t++] = parseInt(n / i); } } } // The vector will be // printed in reverse for (let i = v.length - 1; i >= 0; i--){ document.write(v[i] + " "); }} // Driver codedocument.write("The divisors of 100 are: \n");printDivisors(100); // This code is contributed by _saurabh_jaiswal </script> The divisors of 100 are: n1 2 4 5 10 20 25 50 100 Time Complexity : O(sqrt(n)) Auxiliary Space : O(sqrt(n)) A O(sqrt(n)) Time and O(1) Space Solution : C++ C Java Python3 C# Javascript // A O(sqrt(n)) program that prints all divisors// in sorted order#include <iostream>#include <math.h>using namespace std; // Function to print the divisorsvoid printDivisors(int n){ int i; for (i = 1; i * i < n; i++) { if (n % i == 0) cout<<i<<" "; } if (i - (n / i) == 1) { i--; } for (; i >= 1; i--) { if (n % i == 0) cout<<n / i<<" "; }} // Driver codeint main(){ cout << "The divisors of 100 are: \n"; printDivisors(100); return 0;} // This code is contributed by siteshbiswal // A O(sqrt(n)) program that prints all divisors// in sorted order#include <stdio.h>#include <math.h> // function to print the divisorsvoid printDivisors(int n){ int i; for ( i = 1; i*i < n; i++) { if (n % i == 0) printf("%d ", i); } if(i-(n/i)==1) { i--; } for (; i >= 1; i--) { if (n % i == 0) printf("%d ", n / i); }} /* Driver program to test above function */int main(){ printf("The divisors of 100 are: \n"); printDivisors(100); return 0;} // A O(sqrt(n)) program that prints all// divisors in sorted orderimport java.lang.Math; class GFG{ // Function to print the divisorspublic static void printDivisors(int n){ int i; for( i = 1; i * i < n; i++) { if (n % i == 0) System.out.print(i + " "); } if(i-(n/i)==1) { i--; } for(; i >= 1; i--) { if (n % i == 0) System.out.print(n / i + " "); }} // Driver codepublic static void main(String[] args){ System.out.println("The divisors of 100 are: "); printDivisors(100);}} // This code is contributed by Prakash Veer Singh Tomar. # A O(sqrt(n)) program that prints all divisors# in sorted orderfrom math import * # Function to print the divisorsdef printDivisors (n): i = 1 while (i * i < n): if (n % i == 0): print(i, end = " ") i += 1 for i in range(int(sqrt(n)), 0, -1): if (n % i == 0): print(n // i, end = " ") # Driver Codeprint("The divisors of 100 are: ") printDivisors(100) # This code is contributed by himanshu77 // A O(sqrt(n)) program that prints// all divisors in sorted orderusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print the divisorsstatic void printDivisors(int n){ for(int i = 1; i * i < n; i++) { if (n % i == 0) Console.Write(i + " "); } for(int i = (int)Math.Sqrt(n); i >= 1; i--) { if (n % i == 0) Console.Write(n / i + " "); }} // Driver code public static void Main(string []arg){ Console.Write("The divisors of 100 are: \n"); printDivisors(100);}} // This code is contributed by rutvik_56 <script> // A O(sqrt(n)) program that prints all divisors// in sorted order // function to print the divisorsfunction printDivisors(n){ for (var i = 1; i*i < n; i++) { if (n % i == 0) document.write(i + " "); } for (var i = Math.sqrt(n); i >= 1; i--) { if (n % i == 0) document.write(" " + n / i); }} // Driver program to test above function document.write("The divisors of 100 are: \n"); printDivisors(100); // This code is contributed by simranarora5sos </script> The divisors of 100 are: 1 2 4 5 10 20 25 50 100 Thanks to Mysterious Mind for suggesting the above solution. The if condition between the two loops is used when corner factors in loops condition have a difference of 1(example- factors of 30 (5,6)here,5 will be printed two times; to resolve that issue this step is required. This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar ukasp himanshu77 rutvik_56 divyeshrabadiya07 _saurabh_jaiswal simranarora5sos shivanisinghss2110 gagantomar235 siteshbiswal 191210029 divisors Numbers sieve Mathematical Misc Misc Mathematical Misc Numbers sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
[ { "code": null, "e": 25971, "s": 25943, "text": "\n11 Jan, 2022" }, { "code": null, "e": 26032, "s": 25971, "text": "Given a natural number n, print all distinct divisors of it." }, { "code": null, "e": 26043, "s": 26032, "text": "Examples: " }, { "code": null, "e": 26174, "s": 26043, "text": " Input : n = 10 \n Output: 1 2 5 10\n\n Input: n = 100\n Output: 1 2 4 5 10 20 25 50 100\n\n Input: n = 125\n Output: 1 5 25 125 " }, { "code": null, "e": 26528, "s": 26174, "text": "We strongly recommend referring to the below article as a prerequisite. Find all divisors of a natural number | Set 1In the above post, we had found a way to find all the divisors in O(sqrt(n)).However there is still a minor problem in the solution, can you guess? Yes! the output is not in a sorted fashion which we had got using brute-force technique." }, { "code": null, "e": 26772, "s": 26528, "text": "How to print the output in sorted order? If we observe the output which we had got, we can analyze that the divisors are printed in a zig-zag fashion (small, large pairs). Hence if we store half of them then we can print them in sorted order. " }, { "code": null, "e": 26814, "s": 26772, "text": "Below is an implementation for the same: " }, { "code": null, "e": 26818, "s": 26814, "text": "C++" }, { "code": null, "e": 26823, "s": 26818, "text": "Java" }, { "code": null, "e": 26831, "s": 26823, "text": "Python3" }, { "code": null, "e": 26834, "s": 26831, "text": "C#" }, { "code": null, "e": 26838, "s": 26834, "text": "PHP" }, { "code": null, "e": 26849, "s": 26838, "text": "Javascript" }, { "code": "// A O(sqrt(n)) program that prints all divisors// in sorted order#include <bits/stdc++.h>using namespace std; // function to print the divisorsvoid printDivisors(int n){ // Vector to store half of the divisors vector<int> v; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) printf(\"%d \", i); else { printf(\"%d \", i); // push the second divisor in the vector v.push_back(n / i); } } } // The vector will be printed in reverse for (int i = v.size() - 1; i >= 0; i--) printf(\"%d \", v[i]);} /* Driver program to test above function */int main(){ printf(\"The divisors of 100 are: \\n\"); printDivisors(100); return 0;}", "e": 27670, "s": 26849, "text": null }, { "code": "// A O(sqrt(n)) java program that prints all divisors// in sorted order import java.util.Vector; class Test { // method to print the divisors static void printDivisors(int n) { // Vector to store half of the divisors Vector<Integer> v = new Vector<>(); for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) System.out.printf(\"%d \", i); else { System.out.printf(\"%d \", i); // push the second divisor in the vector v.add(n / i); } } } // The vector will be printed in reverse for (int i = v.size() - 1; i >= 0; i--) System.out.printf(\"%d \", v.get(i)); } // Driver method public static void main(String args[]) { System.out.println(\"The divisors of 100 are: \"); printDivisors(100); }}", "e": 28658, "s": 27670, "text": null }, { "code": "# A O(sqrt(n)) java program that prints# all divisors in sorted orderimport math # Method to print the divisorsdef printDivisors(n) : list = [] # List to store half of the divisors for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : # Check if divisors are equal if (n / i == i) : print (i, end =\" \") else : # Otherwise print both print (i, end =\" \") list.append(int(n / i)) # The list will be printed in reverse for i in list[::-1] : print (i, end =\" \") # Driver methodprint (\"The divisors of 100 are: \")printDivisors(100) # This code is contributed by Gitanjali", "e": 29408, "s": 28658, "text": null }, { "code": "// A O(sqrt(n)) C# program that// prints all divisors in sorted orderusing System; class GFG { // method to print the divisors static void printDivisors(int n) { // Vector to store half // of the divisors int[] v = new int[n]; int t = 0; for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // check if divisors are equal if (n / i == i) Console.Write(i + \" \"); else { Console.Write(i + \" \"); // push the second divisor // in the vector v[t++] = n / i; } } } // The vector will be // printed in reverse for (int i = t - 1; i >= 0; i--) Console.Write(v[i] + \" \"); } // Driver Code public static void Main() { Console.Write(\"The divisors of 100 are: \\n\"); printDivisors(100); }} // This code is contributed// by ChitraNayal", "e": 30443, "s": 29408, "text": null }, { "code": "<?php// A O(sqrt(n)) program that// prints all divisors in// sorted order // function to print// the divisorsfunction printDivisors($n){ // Vector to store half // of the divisors $v; $t = 0; for ($i = 1; $i <= (int)sqrt($n); $i++) { if ($n % $i == 0) { // check if divisors are equal if ((int)$n / $i == $i) echo $i . \" \"; else { echo $i . \" \"; // push the second // divisor in the vector $v[$t++] = (int)$n / $i; } } } // The vector will be // printed in reverse for ($i = count($v) - 1; $i >= 0; $i--) echo $v[$i] . \" \";} // Driver codeecho \"The divisors of 100 are: \\n\";printDivisors(100); // This code is contributed by mits?>", "e": 31281, "s": 30443, "text": null }, { "code": "<script> // A O(sqrt(n)) program that// prints all divisors in// sorted order // function to print// the divisorsfunction printDivisors(n){ // Vector to store half // of the divisors let v = []; let t = 0; for (let i = 1; i <= parseInt(Math.sqrt(n)); i++) { if (n % i == 0) { // check if divisors are equal if (parseInt(n / i) == i) document.write(i + \" \"); else { document.write(i + \" \"); // push the second // divisor in the vector v[t++] = parseInt(n / i); } } } // The vector will be // printed in reverse for (let i = v.length - 1; i >= 0; i--){ document.write(v[i] + \" \"); }} // Driver codedocument.write(\"The divisors of 100 are: \\n\");printDivisors(100); // This code is contributed by _saurabh_jaiswal </script>", "e": 32211, "s": 31281, "text": null }, { "code": null, "e": 32262, "s": 32211, "text": "The divisors of 100 are: n1 2 4 5 10 20 25 50 100 " }, { "code": null, "e": 32320, "s": 32262, "text": "Time Complexity : O(sqrt(n)) Auxiliary Space : O(sqrt(n))" }, { "code": null, "e": 32365, "s": 32320, "text": "A O(sqrt(n)) Time and O(1) Space Solution : " }, { "code": null, "e": 32369, "s": 32365, "text": "C++" }, { "code": null, "e": 32371, "s": 32369, "text": "C" }, { "code": null, "e": 32376, "s": 32371, "text": "Java" }, { "code": null, "e": 32384, "s": 32376, "text": "Python3" }, { "code": null, "e": 32387, "s": 32384, "text": "C#" }, { "code": null, "e": 32398, "s": 32387, "text": "Javascript" }, { "code": "// A O(sqrt(n)) program that prints all divisors// in sorted order#include <iostream>#include <math.h>using namespace std; // Function to print the divisorsvoid printDivisors(int n){ int i; for (i = 1; i * i < n; i++) { if (n % i == 0) cout<<i<<\" \"; } if (i - (n / i) == 1) { i--; } for (; i >= 1; i--) { if (n % i == 0) cout<<n / i<<\" \"; }} // Driver codeint main(){ cout << \"The divisors of 100 are: \\n\"; printDivisors(100); return 0;} // This code is contributed by siteshbiswal", "e": 32955, "s": 32398, "text": null }, { "code": "// A O(sqrt(n)) program that prints all divisors// in sorted order#include <stdio.h>#include <math.h> // function to print the divisorsvoid printDivisors(int n){ int i; for ( i = 1; i*i < n; i++) { if (n % i == 0) printf(\"%d \", i); } if(i-(n/i)==1) { i--; } for (; i >= 1; i--) { if (n % i == 0) printf(\"%d \", n / i); }} /* Driver program to test above function */int main(){ printf(\"The divisors of 100 are: \\n\"); printDivisors(100); return 0;}", "e": 33471, "s": 32955, "text": null }, { "code": "// A O(sqrt(n)) program that prints all// divisors in sorted orderimport java.lang.Math; class GFG{ // Function to print the divisorspublic static void printDivisors(int n){ int i; for( i = 1; i * i < n; i++) { if (n % i == 0) System.out.print(i + \" \"); } if(i-(n/i)==1) { i--; } for(; i >= 1; i--) { if (n % i == 0) System.out.print(n / i + \" \"); }} // Driver codepublic static void main(String[] args){ System.out.println(\"The divisors of 100 are: \"); printDivisors(100);}} // This code is contributed by Prakash Veer Singh Tomar.", "e": 34087, "s": 33471, "text": null }, { "code": "# A O(sqrt(n)) program that prints all divisors# in sorted orderfrom math import * # Function to print the divisorsdef printDivisors (n): i = 1 while (i * i < n): if (n % i == 0): print(i, end = \" \") i += 1 for i in range(int(sqrt(n)), 0, -1): if (n % i == 0): print(n // i, end = \" \") # Driver Codeprint(\"The divisors of 100 are: \") printDivisors(100) # This code is contributed by himanshu77", "e": 34536, "s": 34087, "text": null }, { "code": "// A O(sqrt(n)) program that prints// all divisors in sorted orderusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to print the divisorsstatic void printDivisors(int n){ for(int i = 1; i * i < n; i++) { if (n % i == 0) Console.Write(i + \" \"); } for(int i = (int)Math.Sqrt(n); i >= 1; i--) { if (n % i == 0) Console.Write(n / i + \" \"); }} // Driver code public static void Main(string []arg){ Console.Write(\"The divisors of 100 are: \\n\"); printDivisors(100);}} // This code is contributed by rutvik_56", "e": 35151, "s": 34536, "text": null }, { "code": "<script> // A O(sqrt(n)) program that prints all divisors// in sorted order // function to print the divisorsfunction printDivisors(n){ for (var i = 1; i*i < n; i++) { if (n % i == 0) document.write(i + \" \"); } for (var i = Math.sqrt(n); i >= 1; i--) { if (n % i == 0) document.write(\" \" + n / i); }} // Driver program to test above function document.write(\"The divisors of 100 are: \\n\"); printDivisors(100); // This code is contributed by simranarora5sos </script>", "e": 35676, "s": 35151, "text": null }, { "code": null, "e": 35727, "s": 35676, "text": "The divisors of 100 are: \n1 2 4 5 10 20 25 50 100 " }, { "code": null, "e": 35788, "s": 35727, "text": "Thanks to Mysterious Mind for suggesting the above solution." }, { "code": null, "e": 36004, "s": 35788, "text": "The if condition between the two loops is used when corner factors in loops condition have a difference of 1(example- factors of 30 (5,6)here,5 will be printed two times; to resolve that issue this step is required." }, { "code": null, "e": 36176, "s": 36004, "text": "This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36189, "s": 36176, "text": "Mithun Kumar" }, { "code": null, "e": 36195, "s": 36189, "text": "ukasp" }, { "code": null, "e": 36206, "s": 36195, "text": "himanshu77" }, { "code": null, "e": 36216, "s": 36206, "text": "rutvik_56" }, { "code": null, "e": 36234, "s": 36216, "text": "divyeshrabadiya07" }, { "code": null, "e": 36251, "s": 36234, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36267, "s": 36251, "text": "simranarora5sos" }, { "code": null, "e": 36286, "s": 36267, "text": "shivanisinghss2110" }, { "code": null, "e": 36300, "s": 36286, "text": "gagantomar235" }, { "code": null, "e": 36313, "s": 36300, "text": "siteshbiswal" }, { "code": null, "e": 36323, "s": 36313, "text": "191210029" }, { "code": null, "e": 36332, "s": 36323, "text": "divisors" }, { "code": null, "e": 36340, "s": 36332, "text": "Numbers" }, { "code": null, "e": 36346, "s": 36340, "text": "sieve" }, { "code": null, "e": 36359, "s": 36346, "text": "Mathematical" }, { "code": null, "e": 36364, "s": 36359, "text": "Misc" }, { "code": null, "e": 36369, "s": 36364, "text": "Misc" }, { "code": null, "e": 36382, "s": 36369, "text": "Mathematical" }, { "code": null, "e": 36387, "s": 36382, "text": "Misc" }, { "code": null, "e": 36395, "s": 36387, "text": "Numbers" }, { "code": null, "e": 36401, "s": 36395, "text": "sieve" }, { "code": null, "e": 36499, "s": 36401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36523, "s": 36499, "text": "Merge two sorted arrays" }, { "code": null, "e": 36566, "s": 36523, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36580, "s": 36566, "text": "Prime Numbers" }, { "code": null, "e": 36653, "s": 36580, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 36674, "s": 36653, "text": "Operators in C / C++" }, { "code": null, "e": 36715, "s": 36674, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 36769, "s": 36715, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 36830, "s": 36769, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 36864, "s": 36830, "text": "How to write Regular Expressions?" } ]
How to use multiple UX Widgets in kivy | Python - GeeksforGeeks
19 Oct, 2021 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial – Learn Kivy with Examples. Classical user interface widgets, ready to be assembled to create more complex widgets. There are multiple UX Widgets such as Label, Button, CheckBox, Image, Slider, Progress Bar, Text Input, Toggle button, Switch. Label: The Label widget is for rendering text. It supports ascii and unicode strings. Button: The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). CheckBox: CheckBox is a specific two-state button that can be either checked or unchecked. Image: The Image widget is used to display an image. Slider: The Slider widget looks like a scrollbar. It supports horizontal and vertical orientations, min/max values and a default value. Progress Bar: ProgressBar widget is used to visualize the progress of some task. TextInput: The TextInput widget provides a box for editable plain text. Toggle Button: The ToggleButton widget acts like a checkbox. When you touch or click it, the state toggles between ‘normal’ and ‘down’ (as opposed to a Button that is only ‘down’ as long as it is pressed). Switch: The Switch widget is active or inactive, like a mechanical light switch. Here, we are going to use almost all these UX widgets So that you can understand how to use them in a single code. Basic Approach: 1) import kivy 2) import kivyApp 3) import window 4) Set minimum version(optional) 5) Create the App class 6) Create the .kv file 7) Make the run method/ run the App Implementation of the Approach:.py file: Python3 # Program to Show how to use multiple UX widget # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Here for providing colour to the backgroundfrom kivy.core.window import Window # Setting the window sizeWindow.size = (1120, 630) # Add the App classclass ClassiqueApp(App): def build(FloatLayout): pass # Run the Appif __name__ == '__main__': ClassiqueApp().run() .kv file: Python3 # .kv file implementation of the App # Using Grid layoutGridLayout: cols: 4 rows: 3 padding: 10 # Adding label Label: text: "I am a Label" # Add Button Button: text: "button 1" # Add CheckBox CheckBox: active: True # Add Image Image: source: 'html.png' # Add Slider Slider: min: -100 max: 100 value: 25 # Add progress Bar ProgressBar: min: 50 max: 100 # Add TextInput TextInput: text: "Enter the text" # Add toggle Button ToggleButton: text: " Poetry Mode " # Add Switch Switch: active: True Output: gabaa406 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25575, "s": 25547, "text": "\n19 Oct, 2021" }, { "code": null, "e": 25812, "s": 25575, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. " }, { "code": null, "e": 25863, "s": 25812, "text": "???????? Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 26081, "s": 25865, "text": "Classical user interface widgets, ready to be assembled to create more complex widgets. There are multiple UX Widgets such as Label, Button, CheckBox, Image, Slider, Progress Bar, Text Input, Toggle button, Switch. " }, { "code": null, "e": 26167, "s": 26081, "text": "Label: The Label widget is for rendering text. It supports ascii and unicode strings." }, { "code": null, "e": 26302, "s": 26167, "text": "Button: The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch)." }, { "code": null, "e": 26393, "s": 26302, "text": "CheckBox: CheckBox is a specific two-state button that can be either checked or unchecked." }, { "code": null, "e": 26446, "s": 26393, "text": "Image: The Image widget is used to display an image." }, { "code": null, "e": 26582, "s": 26446, "text": "Slider: The Slider widget looks like a scrollbar. It supports horizontal and vertical orientations, min/max values and a default value." }, { "code": null, "e": 26663, "s": 26582, "text": "Progress Bar: ProgressBar widget is used to visualize the progress of some task." }, { "code": null, "e": 26735, "s": 26663, "text": "TextInput: The TextInput widget provides a box for editable plain text." }, { "code": null, "e": 26941, "s": 26735, "text": "Toggle Button: The ToggleButton widget acts like a checkbox. When you touch or click it, the state toggles between ‘normal’ and ‘down’ (as opposed to a Button that is only ‘down’ as long as it is pressed)." }, { "code": null, "e": 27022, "s": 26941, "text": "Switch: The Switch widget is active or inactive, like a mechanical light switch." }, { "code": null, "e": 27138, "s": 27022, "text": "Here, we are going to use almost all these UX widgets So that you can understand how to use them in a single code. " }, { "code": null, "e": 27321, "s": 27138, "text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import window\n4) Set minimum version(optional)\n5) Create the App class\n6) Create the .kv file \n7) Make the run method/ run the App" }, { "code": null, "e": 27364, "s": 27321, "text": "Implementation of the Approach:.py file: " }, { "code": null, "e": 27372, "s": 27364, "text": "Python3" }, { "code": "# Program to Show how to use multiple UX widget # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # Here for providing colour to the backgroundfrom kivy.core.window import Window # Setting the window sizeWindow.size = (1120, 630) # Add the App classclass ClassiqueApp(App): def build(FloatLayout): pass # Run the Appif __name__ == '__main__': ClassiqueApp().run()", "e": 28003, "s": 27372, "text": null }, { "code": null, "e": 28015, "s": 28003, "text": ".kv file: " }, { "code": null, "e": 28023, "s": 28015, "text": "Python3" }, { "code": "# .kv file implementation of the App # Using Grid layoutGridLayout: cols: 4 rows: 3 padding: 10 # Adding label Label: text: \"I am a Label\" # Add Button Button: text: \"button 1\" # Add CheckBox CheckBox: active: True # Add Image Image: source: 'html.png' # Add Slider Slider: min: -100 max: 100 value: 25 # Add progress Bar ProgressBar: min: 50 max: 100 # Add TextInput TextInput: text: \"Enter the text\" # Add toggle Button ToggleButton: text: \" Poetry Mode \" # Add Switch Switch: active: True ", "e": 28680, "s": 28023, "text": null }, { "code": null, "e": 28690, "s": 28680, "text": "Output: " }, { "code": null, "e": 28701, "s": 28692, "text": "gabaa406" }, { "code": null, "e": 28712, "s": 28701, "text": "Python-gui" }, { "code": null, "e": 28724, "s": 28712, "text": "Python-kivy" }, { "code": null, "e": 28731, "s": 28724, "text": "Python" }, { "code": null, "e": 28829, "s": 28731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28847, "s": 28829, "text": "Python Dictionary" }, { "code": null, "e": 28879, "s": 28847, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28901, "s": 28879, "text": "Enumerate() in Python" }, { "code": null, "e": 28943, "s": 28901, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28969, "s": 28943, "text": "Python String | replace()" }, { "code": null, "e": 28998, "s": 28969, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29042, "s": 28998, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29079, "s": 29042, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29115, "s": 29079, "text": "Convert integer to string in Python" } ]
SimpleAdapter in Android with Example - GeeksforGeeks
16 Feb, 2021 In Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an easy adapter to map static data to views defined in our XML file(UI component) and is used for customization of List or Grid items. Here we use an ArrayList of Map (e.g. hashmap, mutable map, etc.) for data-backing. Each entry in an ArrayList is corresponding to one row of a list. The Map contains the data for each row. Now to display the row we need a view for which we used to specify a custom list item file (an XML file). SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) ***Here context, data, resource, from, and to are five parameters*** Parameters DataType Explanation List<? extends Map<String, ?>> *** it means a List of Maps whose key‘s type is String and Value can be any datatype. int ***Integer Datatype A sample image is given below to get an idea about what we are going to do in this article. In this project, we are going to make this application which has a list of some fruits and in each row of the list has a fruit image and name. Note that we are going to implement this same project in both Kotlin and Java languages. Now you choose your preferred language. Step 1: Create a New Project Open Android Studio > Create New Project > Select an Empty Activity > Give a project name (Here our project name is “GFG_SimpleAdapter“). *** Here you can choose either Kotlin or Java which you preferred and chose the API level according to your choice. ***After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link: CLICK HERE ***please note that it is optional*** Step 2: Working with the activity_main.xml file In the activity_main.xml file, create a ListView inside a RelativeLayout. 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" tools:context=".MainActivity"> <!--Creating a ListView--> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="#000000" android:dividerHeight="3dp" android:padding="5dp" /> </RelativeLayout> activity_main.xml Interface: Step 3: Create another XML file (named list_row_items) and create UI for each row of the ListView Create a new Layout Resource file and name it as list_row_items. Below is the code for the list_row_items.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!--Creating a ImageView--> <ImageView android:id="@+id/imageView" android:layout_width="120dp" android:layout_height="120dp" android:layout_margin="10dp" android:scaleType="fitCenter" android:src="@drawable/ic_launcher_background" /> <!--Creating a TextView--> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:layout_marginRight="20dp" android:layout_toRightOf="@+id/imageView" android:gravity="center" android:padding="5dp" android:text="Text View" android:textColor="#808080" android:textSize="40sp" android:textStyle="bold|italic" /> </RelativeLayout> list_row_items.xml Interface: Step 4: Working with the MainActivity file Here we will show you how to implement SimpleAdapter both in Java and Kotlin. Now you choose your preferred one. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. Java Kotlin import android.os.Bundle;import android.widget.ListView;import android.widget.SimpleAdapter;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashMap; public class MainActivity extends AppCompatActivity { ListView listView; // creating a String type array (fruitNames) // which contains names of different fruits' images String fruitNames[] = {"Banana", "Grape", "Guava", "Mango", "Orange", "Watermelon"}; // creating an Integer type array (fruitImageIds) which // contains IDs of different fruits' images int fruitImageIds[] = {R.drawable.banana, R.drawable.grape, R.drawable.guava, R.drawable.mango, R.drawable.orange, R.drawable.watermelon}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Binding the ListView of activity_main.xml file // with this java code in MainActivity.java listView = findViewById(R.id.listView); // creating an ArrayList of HashMap.The kEY of the HashMap // is a String and VALUE is of any datatype(Object) ArrayList<HashMap<String, Object>> list = new ArrayList<>(); // By a for loop, entering different types of data in HashMap, // and adding this map including it's datas into the ArrayList // as list item and this list is the second parameter of the SimpleAdapter for (int i = 0; i < fruitNames.length; i++) { // creating an Object of HashMap class HashMap<String, Object> map = new HashMap<>(); // Data entry in HashMap map.put("fruitName", fruitNames[i]); map.put("fruitImage", fruitImageIds[i]); // adding the HashMap to the ArrayList list.add(map); } // creating A string type array(from) which contains // column names for each View in each row of the list // and this array(form) is the fourth parameter of the SimpleAdapter String[] from = {"fruitName", "fruitImage"}; // creating an integer type array(to) which contains // id of each View in each row of the list // and this array(form) is the fifth parameter of the SimpleAdapter int to[] = {R.id.textView, R.id.imageView}; // creating an Object of SimpleAdapter class and // passing all the required parameters SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to); // now setting the simpleAdapter to the ListView listView.setAdapter(simpleAdapter); }} import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ListViewimport android.widget.SimpleAdapterimport java.util.ArrayListimport java.util.HashMap class MainActivity : AppCompatActivity() { private lateinit var listView:ListView // creating a String type array // (fruitNames) which contains // names of different fruits' images private val fruitNames=arrayOf("Banana","Grape","Guava","Mango","Orange","Watermelon") // creating an Integer type array (fruitImageIds) which // contains IDs of different fruits' images private val fruitImageIds=arrayOf(R.drawable.banana, R.drawable.grape, R.drawable.guava, R.drawable.mango, R.drawable.orange, R.drawable.watermelon) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // ViewBinding the ListView of activity_main.xml file // with this kotlin code in MainActivity.kt listView=findViewById(R.id.listView) // creating an ArrayList of HashMap.The kEY of the HashMap is // a String and VALUE is of any datatype(Any) val list=ArrayList<HashMap<String,Any>>() // By a for loop, entering different types of data in HashMap, // and adding this map including it's datas into the ArrayList // as list item and this list is the second parameter of the SimpleAdapter for(i in fruitNames.indices){ val map=HashMap<String,Any>() // Data entry in HashMap map["fruitName"] = fruitNames[i] map["fruitImage"]=fruitImageIds[i] // adding the HashMap to the ArrayList list.add(map) } // creating A string type array(from) which contains // column names for each View in each row of the list // and this array(form) is the fourth parameter of the SimpleAdapter val from=arrayOf("fruitName","fruitImage") // creating an integer type array(to) which contains id of each View in each row of the list and this array(form) is the fifth parameter of the SimpleAdapter*/ val to= intArrayOf(R.id.textView,R.id.imageView) // creating an Object of SimpleAdapter // class and passing // all the required parameters val simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to) // now setting the simpleAdapter // to the ListView listView.adapter = simpleAdapter }} Thus SimpleAdapter holds data and sends the data to the adapter view then the view can take the data from the adapter view and shows the data on the ListView which we have created earlier. ***Please note you have to choose any one language between Java and Kotlin as MainActivity for a particular project*** user_xstb Picked Technical Scripter 2020 Android Java Kotlin Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 25705, "s": 25677, "text": "\n16 Feb, 2021" }, { "code": null, "e": 26483, "s": 25705, "text": "In Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an easy adapter to map static data to views defined in our XML file(UI component) and is used for customization of List or Grid items. Here we use an ArrayList of Map (e.g. hashmap, mutable map, etc.) for data-backing. Each entry in an ArrayList is corresponding to one row of a list. The Map contains the data for each row. Now to display the row we need a view for which we used to specify a custom list item file (an XML file)." }, { "code": null, "e": 26590, "s": 26483, "text": "SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)" }, { "code": null, "e": 26667, "s": 26590, "text": "***Here context, data, resource, from, and to are five parameters*** " }, { "code": null, "e": 26720, "s": 26669, "text": "Parameters " }, { "code": null, "e": 26729, "s": 26720, "text": "DataType" }, { "code": null, "e": 26741, "s": 26729, "text": "Explanation" }, { "code": null, "e": 26772, "s": 26741, "text": "List<? extends Map<String, ?>>" }, { "code": null, "e": 26858, "s": 26772, "text": "*** it means a List of Maps whose key‘s type is String and Value can be any datatype." }, { "code": null, "e": 26863, "s": 26858, "text": " int" }, { "code": null, "e": 26883, "s": 26863, "text": "***Integer Datatype" }, { "code": null, "e": 27249, "s": 26883, "text": "A sample image is given below to get an idea about what we are going to do in this article. In this project, we are going to make this application which has a list of some fruits and in each row of the list has a fruit image and name. Note that we are going to implement this same project in both Kotlin and Java languages. Now you choose your preferred language. " }, { "code": null, "e": 27278, "s": 27249, "text": "Step 1: Create a New Project" }, { "code": null, "e": 27416, "s": 27278, "text": "Open Android Studio > Create New Project > Select an Empty Activity > Give a project name (Here our project name is “GFG_SimpleAdapter“)." }, { "code": null, "e": 27532, "s": 27416, "text": "*** Here you can choose either Kotlin or Java which you preferred and chose the API level according to your choice." }, { "code": null, "e": 27838, "s": 27532, "text": "***After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:" }, { "code": null, "e": 27849, "s": 27838, "text": "CLICK HERE" }, { "code": null, "e": 27887, "s": 27849, "text": "***please note that it is optional***" }, { "code": null, "e": 27935, "s": 27887, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 28059, "s": 27935, "text": "In the activity_main.xml file, create a ListView inside a RelativeLayout. Below is the code for the activity_main.xml file." }, { "code": null, "e": 28063, "s": 28059, "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\" tools:context=\".MainActivity\"> <!--Creating a ListView--> <ListView android:id=\"@+id/listView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:divider=\"#000000\" android:dividerHeight=\"3dp\" android:padding=\"5dp\" /> </RelativeLayout>", "e": 28629, "s": 28063, "text": null }, { "code": null, "e": 28658, "s": 28629, "text": "activity_main.xml Interface:" }, { "code": null, "e": 28756, "s": 28658, "text": "Step 3: Create another XML file (named list_row_items) and create UI for each row of the ListView" }, { "code": null, "e": 28823, "s": 28756, "text": "Create a new Layout Resource file and name it as list_row_items. " }, { "code": null, "e": 28875, "s": 28823, "text": "Below is the code for the list_row_items.xml file. " }, { "code": null, "e": 28879, "s": 28875, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--Creating a ImageView--> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"120dp\" android:layout_height=\"120dp\" android:layout_margin=\"10dp\" android:scaleType=\"fitCenter\" android:src=\"@drawable/ic_launcher_background\" /> <!--Creating a TextView--> <TextView android:id=\"@+id/textView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"40dp\" android:layout_marginRight=\"20dp\" android:layout_toRightOf=\"@+id/imageView\" android:gravity=\"center\" android:padding=\"5dp\" android:text=\"Text View\" android:textColor=\"#808080\" android:textSize=\"40sp\" android:textStyle=\"bold|italic\" /> </RelativeLayout>", "e": 29884, "s": 28879, "text": null }, { "code": null, "e": 29914, "s": 29884, "text": "list_row_items.xml Interface:" }, { "code": null, "e": 29958, "s": 29914, "text": "Step 4: Working with the MainActivity file " }, { "code": null, "e": 30191, "s": 29958, "text": "Here we will show you how to implement SimpleAdapter both in Java and Kotlin. Now you choose your preferred one. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 30196, "s": 30191, "text": "Java" }, { "code": null, "e": 30203, "s": 30196, "text": "Kotlin" }, { "code": "import android.os.Bundle;import android.widget.ListView;import android.widget.SimpleAdapter;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashMap; public class MainActivity extends AppCompatActivity { ListView listView; // creating a String type array (fruitNames) // which contains names of different fruits' images String fruitNames[] = {\"Banana\", \"Grape\", \"Guava\", \"Mango\", \"Orange\", \"Watermelon\"}; // creating an Integer type array (fruitImageIds) which // contains IDs of different fruits' images int fruitImageIds[] = {R.drawable.banana, R.drawable.grape, R.drawable.guava, R.drawable.mango, R.drawable.orange, R.drawable.watermelon}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Binding the ListView of activity_main.xml file // with this java code in MainActivity.java listView = findViewById(R.id.listView); // creating an ArrayList of HashMap.The kEY of the HashMap // is a String and VALUE is of any datatype(Object) ArrayList<HashMap<String, Object>> list = new ArrayList<>(); // By a for loop, entering different types of data in HashMap, // and adding this map including it's datas into the ArrayList // as list item and this list is the second parameter of the SimpleAdapter for (int i = 0; i < fruitNames.length; i++) { // creating an Object of HashMap class HashMap<String, Object> map = new HashMap<>(); // Data entry in HashMap map.put(\"fruitName\", fruitNames[i]); map.put(\"fruitImage\", fruitImageIds[i]); // adding the HashMap to the ArrayList list.add(map); } // creating A string type array(from) which contains // column names for each View in each row of the list // and this array(form) is the fourth parameter of the SimpleAdapter String[] from = {\"fruitName\", \"fruitImage\"}; // creating an integer type array(to) which contains // id of each View in each row of the list // and this array(form) is the fifth parameter of the SimpleAdapter int to[] = {R.id.textView, R.id.imageView}; // creating an Object of SimpleAdapter class and // passing all the required parameters SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to); // now setting the simpleAdapter to the ListView listView.setAdapter(simpleAdapter); }}", "e": 32907, "s": 30203, "text": null }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.ListViewimport android.widget.SimpleAdapterimport java.util.ArrayListimport java.util.HashMap class MainActivity : AppCompatActivity() { private lateinit var listView:ListView // creating a String type array // (fruitNames) which contains // names of different fruits' images private val fruitNames=arrayOf(\"Banana\",\"Grape\",\"Guava\",\"Mango\",\"Orange\",\"Watermelon\") // creating an Integer type array (fruitImageIds) which // contains IDs of different fruits' images private val fruitImageIds=arrayOf(R.drawable.banana, R.drawable.grape, R.drawable.guava, R.drawable.mango, R.drawable.orange, R.drawable.watermelon) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // ViewBinding the ListView of activity_main.xml file // with this kotlin code in MainActivity.kt listView=findViewById(R.id.listView) // creating an ArrayList of HashMap.The kEY of the HashMap is // a String and VALUE is of any datatype(Any) val list=ArrayList<HashMap<String,Any>>() // By a for loop, entering different types of data in HashMap, // and adding this map including it's datas into the ArrayList // as list item and this list is the second parameter of the SimpleAdapter for(i in fruitNames.indices){ val map=HashMap<String,Any>() // Data entry in HashMap map[\"fruitName\"] = fruitNames[i] map[\"fruitImage\"]=fruitImageIds[i] // adding the HashMap to the ArrayList list.add(map) } // creating A string type array(from) which contains // column names for each View in each row of the list // and this array(form) is the fourth parameter of the SimpleAdapter val from=arrayOf(\"fruitName\",\"fruitImage\") // creating an integer type array(to) which contains id of each View in each row of the list and this array(form) is the fifth parameter of the SimpleAdapter*/ val to= intArrayOf(R.id.textView,R.id.imageView) // creating an Object of SimpleAdapter // class and passing // all the required parameters val simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to) // now setting the simpleAdapter // to the ListView listView.adapter = simpleAdapter }}", "e": 35673, "s": 32907, "text": null }, { "code": null, "e": 35863, "s": 35673, "text": "Thus SimpleAdapter holds data and sends the data to the adapter view then the view can take the data from the adapter view and shows the data on the ListView which we have created earlier. " }, { "code": null, "e": 35983, "s": 35863, "text": "***Please note you have to choose any one language between Java and Kotlin as MainActivity for a particular project***" }, { "code": null, "e": 35993, "s": 35983, "text": "user_xstb" }, { "code": null, "e": 36000, "s": 35993, "text": "Picked" }, { "code": null, "e": 36024, "s": 36000, "text": "Technical Scripter 2020" }, { "code": null, "e": 36032, "s": 36024, "text": "Android" }, { "code": null, "e": 36037, "s": 36032, "text": "Java" }, { "code": null, "e": 36044, "s": 36037, "text": "Kotlin" }, { "code": null, "e": 36063, "s": 36044, "text": "Technical Scripter" }, { "code": null, "e": 36068, "s": 36063, "text": "Java" }, { "code": null, "e": 36076, "s": 36068, "text": "Android" }, { "code": null, "e": 36174, "s": 36076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36232, "s": 36174, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 36275, "s": 36232, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 36313, "s": 36275, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 36346, "s": 36313, "text": "Services in Android with Example" }, { "code": null, "e": 36377, "s": 36346, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 36392, "s": 36377, "text": "Arrays in Java" }, { "code": null, "e": 36436, "s": 36392, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36458, "s": 36436, "text": "For-each loop in Java" }, { "code": null, "e": 36509, "s": 36458, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Activity Aliases in Android to Preserve Launchers - GeeksforGeeks
21 Nov, 2021 Before moving on to the topic, pick up your mobile phones and count the number of applications that you are having on your device. All of you must have more than 30 applications on average. But out of these 30 apps, we only use 5–6 applications on a regular basis. Other applications are rarely used but are important. So, what we do is, create shortcuts of frequently used applications on our home screen or on our phone’s main screen. These launchers are used to launch the Launcher Activity of that particular application. Hold on! So, in this blog, we will learn how to create shortcuts for applications on the home screen? No way, we all know it very well. So, whenever we launch a mobile application from the shortcuts, then the Launcher Activity is called. The duty of the shortcut is to keep or store your launcher and whenever you start an app then the shortcut will launch the launcher or simply MainActivity for you. But the situation gets more tricky when you change the Launcher Activity of your application. So, try to change the Launcher Activity of your application and run the application on your device. Do you still find the shortcut on the home screen? Hey, what has just happened? Where has the shortcut gone? Don’t worry, at the end of this blog, you will come to know the answers to all these questions. So, in this blog, we will learn about Activity Alias in Android. Let’s get started. We have seen that, if we change the Launcher Activity of our application, then the shortcut of the application on the home screen will be lost. But why should anyone change the Launcher Activity? The reason is very simple, whenever you are making a new update for your application, there may be situations where you may have to change your Launcher Activity due to some new features or there may be situations where you have changed the package name and the corresponding Activity name. So, in this case, also, the name of your Launcher Activity will be changed while the content remains the same. \ Let’s make a project to understand the problem in a better way. Create a project in Android Studio and name your MainActivity as PrevActivity (you can use another name also). Following is the code for my activity_prev.xml file: <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PrevActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World! I am in Previous Activity" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> We don’t need to add any code for the PrevActivity.kt file. Now create another Activity with activity name as NewActivity. The code for the activity_new.xml is: <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".NewActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World! I am in New Activity" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> We have not written any code in the NewActivity.kt file. Now, open the AndroidManifest.xml file. The following code will be there: <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=".NewActivity"> </activity> <activity android:name=".PrevActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity></application> Here, our PrevActivity is the Launcher activity because we have used the <intent-filter> in the PrevActivity tag. So, whenever we will launch the application, then the PrevActivity will be launched. Now, install the application on your device and make a shortcut of the app on your home screen. After creating a shortcut, change the Launcher activity to NewActivity. So, the code of our AndroidManifest.xml file will be changed to: <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=".PrevActivity"> </activity> <activity android:name=".NewActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity></application> Now, run the app and try to find the shortcut that you have created on the home screen. You will not find any shortcuts on the home screen. Whenever we make a shortcut of a particular application on our home screen then that shortcut remembers the name of the Launcher Activity i.e. in our example the name is PrevActivity: <activity android:name=".PrevActivity"> Now, if you will change the name of the Launcher Activity i.e. our name changed to: <activity android:name=".NewActivity"> The problem arises here, the shortcut is having the name PrevActivity but now the name has changed to NewActivity and it gets confused and the shortcut is deleted from the home screen. So, in order to keep the shortcut on the home screen, even after the change in the Launcher Activity name, we use the concept of Activity-Alias. The <activity-alias> is used to launch an Activity by preserving the launchers. So, by using the <activity-alias> you can change your Launcher Activity and the shortcut launcher will also be preserved on the home screen. But how to use this Activity-Alias? Just use the below code in your AndroidManifest.xml file: <activity android:name=".PrevActivity"/><activity android:name=".NewActivity"/><activity-alias android:name=".MainActivity" android:targetActivity=".PrevActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity-alias> Here, we have used the <activity-alias> tag to declare our Launcher Activity. Whenever the application will be launched, then the PrevActivity will be launched because the android:targetActivity=”.PrevActivity” is used to define the targeted activity when the Launcher is called. Now, make a shortcut of the application on your home screen and then change the Launcher Activity to NewActivity and run the app. Now, you can see that after changing the Launcher Activity, our shortcut is still there on the home screen. But what’s the reason behind this? So, in our case when you make a shortcut of our application, then the name will be remembered i.e. in our case “MainActivity”: android:name=".MainActivity" So, whenever the Launcher will be called, then the shortcut will search for the name “MainActivity” and if it finds the same then it will launch the Activity that is written in: android:targetActivity=".PrevActivity" So, change the target activity to your choice and keep the name the same in the <activity-alias>. Now, try to change the name in the <activity-alias> and run the application. You will find the same problem i.e. the shortcut will be removed from the screen because the name has been changed. Note: In order to use <activity-alias> you need to declare all your Activities (including the Launcher Activity) above the <activity-alias> tag and not below the <activity-alias> tag. Here are the features provided by the <activity-alias>, apart from preserving the Launcher: <activity-alias android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:label="string resource" android:name="string" android:permission="string" android:targetActivity="string" > . . .</activity-alias> android:enabled: The android: enabled is used to tell whether the targeted activity can be instantiated by the system or not. If not then the value will be false otherwise true. By default, it is true for Activity and alias but in order to launch an Activity, both these values must be true at a time.android:exported: It is used to tell whether or not the targetedActivity can be launched by the components of other applications. If not, then the value will be false, otherwise, it is true.android:icon: It sets the icon for the Targeted Activity that is presented to the user using an alias.android:label: When the alias is presented to the user then this android:label is used to set a user-readable text for the alias.android:name: It is used to uniquely identify an alias by writing a fully classified class name.android:permission: Here, the name of the permission is present that is need for a targeted activity to be launched by the alias.android:targetActivity: It is used to specify the Activity name that is to be launched with the help of the alias. android:enabled: The android: enabled is used to tell whether the targeted activity can be instantiated by the system or not. If not then the value will be false otherwise true. By default, it is true for Activity and alias but in order to launch an Activity, both these values must be true at a time. android:exported: It is used to tell whether or not the targetedActivity can be launched by the components of other applications. If not, then the value will be false, otherwise, it is true. android:icon: It sets the icon for the Targeted Activity that is presented to the user using an alias. android:label: When the alias is presented to the user then this android:label is used to set a user-readable text for the alias. android:name: It is used to uniquely identify an alias by writing a fully classified class name. android:permission: Here, the name of the permission is present that is need for a targeted activity to be launched by the alias. android:targetActivity: It is used to specify the Activity name that is to be launched with the help of the alias. I hope that you have learned something new in this blog. Let’s recap. In this blog, we learned the concept of <activity-alias>. The <activity-alias> is used to preserver launchers in the Android Application. By using the <activity-alias>, we can change the Launcher Activity and our shortcut of the application will remain at the same place on the home screen. sagar0719kumar gulshankumarar231 Picked TrueGeek-2021 Android TrueGeek 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? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? Basics of API Testing Using Postman SQL Statement to Remove Part of a String Types of Internet Protocols
[ { "code": null, "e": 26406, "s": 26378, "text": "\n21 Nov, 2021" }, { "code": null, "e": 27817, "s": 26406, "text": "Before moving on to the topic, pick up your mobile phones and count the number of applications that you are having on your device. All of you must have more than 30 applications on average. But out of these 30 apps, we only use 5–6 applications on a regular basis. Other applications are rarely used but are important. So, what we do is, create shortcuts of frequently used applications on our home screen or on our phone’s main screen. These launchers are used to launch the Launcher Activity of that particular application. Hold on! So, in this blog, we will learn how to create shortcuts for applications on the home screen? No way, we all know it very well. So, whenever we launch a mobile application from the shortcuts, then the Launcher Activity is called. The duty of the shortcut is to keep or store your launcher and whenever you start an app then the shortcut will launch the launcher or simply MainActivity for you. But the situation gets more tricky when you change the Launcher Activity of your application. So, try to change the Launcher Activity of your application and run the application on your device. Do you still find the shortcut on the home screen? Hey, what has just happened? Where has the shortcut gone? Don’t worry, at the end of this blog, you will come to know the answers to all these questions. So, in this blog, we will learn about Activity Alias in Android. Let’s get started." }, { "code": null, "e": 28417, "s": 27817, "text": "We have seen that, if we change the Launcher Activity of our application, then the shortcut of the application on the home screen will be lost. But why should anyone change the Launcher Activity? The reason is very simple, whenever you are making a new update for your application, there may be situations where you may have to change your Launcher Activity due to some new features or there may be situations where you have changed the package name and the corresponding Activity name. So, in this case, also, the name of your Launcher Activity will be changed while the content remains the same. \\" }, { "code": null, "e": 28645, "s": 28417, "text": "Let’s make a project to understand the problem in a better way. Create a project in Android Studio and name your MainActivity as PrevActivity (you can use another name also). Following is the code for my activity_prev.xml file:" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".PrevActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World! I am in Previous Activity\" android:textSize=\"24sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 29526, "s": 28645, "text": null }, { "code": null, "e": 29687, "s": 29526, "text": "We don’t need to add any code for the PrevActivity.kt file. Now create another Activity with activity name as NewActivity. The code for the activity_new.xml is:" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".NewActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World! I am in New Activity\" android:textSize=\"24sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 30562, "s": 29687, "text": null }, { "code": null, "e": 30693, "s": 30562, "text": "We have not written any code in the NewActivity.kt file. Now, open the AndroidManifest.xml file. The following code will be there:" }, { "code": "<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=\".NewActivity\"> </activity> <activity android:name=\".PrevActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\"/> <category android:name=\"android.intent.category.LAUNCHER\"/> </intent-filter> </activity></application>", "e": 31260, "s": 30693, "text": null }, { "code": null, "e": 31692, "s": 31260, "text": "Here, our PrevActivity is the Launcher activity because we have used the <intent-filter> in the PrevActivity tag. So, whenever we will launch the application, then the PrevActivity will be launched. Now, install the application on your device and make a shortcut of the app on your home screen. After creating a shortcut, change the Launcher activity to NewActivity. So, the code of our AndroidManifest.xml file will be changed to:" }, { "code": "<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=\".PrevActivity\"> </activity> <activity android:name=\".NewActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\"/> <category android:name=\"android.intent.category.LAUNCHER\"/> </intent-filter> </activity></application>", "e": 32259, "s": 31692, "text": null }, { "code": null, "e": 32399, "s": 32259, "text": "Now, run the app and try to find the shortcut that you have created on the home screen. You will not find any shortcuts on the home screen." }, { "code": null, "e": 32583, "s": 32399, "text": "Whenever we make a shortcut of a particular application on our home screen then that shortcut remembers the name of the Launcher Activity i.e. in our example the name is PrevActivity:" }, { "code": "<activity android:name=\".PrevActivity\">", "e": 32623, "s": 32583, "text": null }, { "code": null, "e": 32707, "s": 32623, "text": "Now, if you will change the name of the Launcher Activity i.e. our name changed to:" }, { "code": "<activity android:name=\".NewActivity\">", "e": 32746, "s": 32707, "text": null }, { "code": null, "e": 32931, "s": 32746, "text": "The problem arises here, the shortcut is having the name PrevActivity but now the name has changed to NewActivity and it gets confused and the shortcut is deleted from the home screen." }, { "code": null, "e": 33391, "s": 32931, "text": "So, in order to keep the shortcut on the home screen, even after the change in the Launcher Activity name, we use the concept of Activity-Alias. The <activity-alias> is used to launch an Activity by preserving the launchers. So, by using the <activity-alias> you can change your Launcher Activity and the shortcut launcher will also be preserved on the home screen. But how to use this Activity-Alias? Just use the below code in your AndroidManifest.xml file:" }, { "code": "<activity android:name=\".PrevActivity\"/><activity android:name=\".NewActivity\"/><activity-alias android:name=\".MainActivity\" android:targetActivity=\".PrevActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter></activity-alias>", "e": 33754, "s": 33391, "text": null }, { "code": null, "e": 34035, "s": 33754, "text": "Here, we have used the <activity-alias> tag to declare our Launcher Activity. Whenever the application will be launched, then the PrevActivity will be launched because the android:targetActivity=”.PrevActivity” is used to define the targeted activity when the Launcher is called. " }, { "code": null, "e": 34308, "s": 34035, "text": "Now, make a shortcut of the application on your home screen and then change the Launcher Activity to NewActivity and run the app. Now, you can see that after changing the Launcher Activity, our shortcut is still there on the home screen. But what’s the reason behind this?" }, { "code": null, "e": 34435, "s": 34308, "text": "So, in our case when you make a shortcut of our application, then the name will be remembered i.e. in our case “MainActivity”:" }, { "code": "android:name=\".MainActivity\"", "e": 34464, "s": 34435, "text": null }, { "code": null, "e": 34643, "s": 34464, "text": "So, whenever the Launcher will be called, then the shortcut will search for the name “MainActivity” and if it finds the same then it will launch the Activity that is written in: " }, { "code": "android:targetActivity=\".PrevActivity\"", "e": 34682, "s": 34643, "text": null }, { "code": null, "e": 34974, "s": 34682, "text": "So, change the target activity to your choice and keep the name the same in the <activity-alias>. Now, try to change the name in the <activity-alias> and run the application. You will find the same problem i.e. the shortcut will be removed from the screen because the name has been changed. " }, { "code": null, "e": 35158, "s": 34974, "text": "Note: In order to use <activity-alias> you need to declare all your Activities (including the Launcher Activity) above the <activity-alias> tag and not below the <activity-alias> tag." }, { "code": null, "e": 35250, "s": 35158, "text": "Here are the features provided by the <activity-alias>, apart from preserving the Launcher:" }, { "code": "<activity-alias android:enabled=[\"true\" | \"false\"] android:exported=[\"true\" | \"false\"] android:icon=\"drawable resource\" android:label=\"string resource\" android:name=\"string\" android:permission=\"string\" android:targetActivity=\"string\" > . . .</activity-alias>", "e": 35602, "s": 35250, "text": null }, { "code": null, "e": 36664, "s": 35602, "text": "android:enabled: The android: enabled is used to tell whether the targeted activity can be instantiated by the system or not. If not then the value will be false otherwise true. By default, it is true for Activity and alias but in order to launch an Activity, both these values must be true at a time.android:exported: It is used to tell whether or not the targetedActivity can be launched by the components of other applications. If not, then the value will be false, otherwise, it is true.android:icon: It sets the icon for the Targeted Activity that is presented to the user using an alias.android:label: When the alias is presented to the user then this android:label is used to set a user-readable text for the alias.android:name: It is used to uniquely identify an alias by writing a fully classified class name.android:permission: Here, the name of the permission is present that is need for a targeted activity to be launched by the alias.android:targetActivity: It is used to specify the Activity name that is to be launched with the help of the alias." }, { "code": null, "e": 36966, "s": 36664, "text": "android:enabled: The android: enabled is used to tell whether the targeted activity can be instantiated by the system or not. If not then the value will be false otherwise true. By default, it is true for Activity and alias but in order to launch an Activity, both these values must be true at a time." }, { "code": null, "e": 37157, "s": 36966, "text": "android:exported: It is used to tell whether or not the targetedActivity can be launched by the components of other applications. If not, then the value will be false, otherwise, it is true." }, { "code": null, "e": 37260, "s": 37157, "text": "android:icon: It sets the icon for the Targeted Activity that is presented to the user using an alias." }, { "code": null, "e": 37390, "s": 37260, "text": "android:label: When the alias is presented to the user then this android:label is used to set a user-readable text for the alias." }, { "code": null, "e": 37487, "s": 37390, "text": "android:name: It is used to uniquely identify an alias by writing a fully classified class name." }, { "code": null, "e": 37617, "s": 37487, "text": "android:permission: Here, the name of the permission is present that is need for a targeted activity to be launched by the alias." }, { "code": null, "e": 37732, "s": 37617, "text": "android:targetActivity: It is used to specify the Activity name that is to be launched with the help of the alias." }, { "code": null, "e": 38093, "s": 37732, "text": "I hope that you have learned something new in this blog. Let’s recap. In this blog, we learned the concept of <activity-alias>. The <activity-alias> is used to preserver launchers in the Android Application. By using the <activity-alias>, we can change the Launcher Activity and our shortcut of the application will remain at the same place on the home screen." }, { "code": null, "e": 38108, "s": 38093, "text": "sagar0719kumar" }, { "code": null, "e": 38126, "s": 38108, "text": "gulshankumarar231" }, { "code": null, "e": 38133, "s": 38126, "text": "Picked" }, { "code": null, "e": 38147, "s": 38133, "text": "TrueGeek-2021" }, { "code": null, "e": 38155, "s": 38147, "text": "Android" }, { "code": null, "e": 38164, "s": 38155, "text": "TrueGeek" }, { "code": null, "e": 38172, "s": 38164, "text": "Android" }, { "code": null, "e": 38270, "s": 38172, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38308, "s": 38270, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 38347, "s": 38308, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38397, "s": 38347, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 38448, "s": 38397, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 38490, "s": 38448, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 38535, "s": 38490, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 38592, "s": 38535, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 38628, "s": 38592, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 38669, "s": 38628, "text": "SQL Statement to Remove Part of a String" } ]
Python | Count occurrence of all elements of list in a tuple - GeeksforGeeks
15 Mar, 2019 Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Approach The first approach is the naive approach. Use a for loop and traverse through the given list and count the occurrence of each item of tuple in a list. Finally, return the count. # Python3 Program to count occurrence # of all elements of list in a tuplefrom collections import Counter def countOccurrence(tup, lst): count = 0 for item in tup: if item in lst: count+= 1 return count # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst)) 3 Approach #2 : Using CounterFrom Python Collections module, import counter to solve the given problem. A Counter is a container that keeps track of how many times equivalent values are added. Having saved the resultant in ‘counts’, we use a for loop and count how many times each item in list occurs in ‘counts’ and sum it to give the final output. # Python3 Program to count occurrence # of all elements of list in a tuplefrom collections import Counter def countOccurrence(tup, lst): counts = Counter(tup) return sum(counts[i] for i in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst)) 3 Approach #3 : Using SetAnother method of solving the given problem is using set data structure. Simply convert the given list into a set, which removes all duplicates. And now, for each item of list, count its occurrence in tuple and sum them. # Python3 Program to count occurrence # of all elements of list in a tuple def countOccurrence(tup, lst): lst = set(lst) return sum(1 for x in tup if x in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst)) 3 Approach #4 : Using Python dictionaryGet each item of tuple and its frequency as key:value pair in Python dictionary, then using a for loop, for each item of list, count its occurrence in tuple and sum them. # Python3 Program to count occurrence # of all elements of list in a tuple def countOccurrence(tup, lst): dct = {} for i in tup: if not dct.get(i): dct[i] = 0 dct[i] += 1 return sum(dct.get(i, 0) for i in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst)) 3 Approach #5 : Python numpy.in1d()Python numpy gives us a direct method to find the solution for the given problem, and that is numpy.in1d(). This method test whether each element of a 1-D array is also present in a second array. Since list is also a 1-D array, this method can be applied here. # Python3 Program to count occurrence # of all elements of list in a tupleimport numpy as np def countOccurrence(tup, lst): return np.in1d(tup, lst).sum() # Driver Codetup = ('a', 'a', 'c', 'b', 'd') lst = ['a', 'b']print(countOccurrence(tup, lst)) 3 Python tuple-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": "\n15 Mar, 2019" }, { "code": null, "e": 25659, "s": 25537, "text": "Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple." }, { "code": null, "e": 25669, "s": 25659, "text": "Examples:" }, { "code": null, "e": 25831, "s": 25669, "text": "Input : tuple = ('a', 'a', 'c', 'b', 'd')\n list = ['a', 'b']\nOutput : 3 \n\nInput : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4)\n list = [1, 4, 7]\nOutput : 6\n" }, { "code": null, "e": 25861, "s": 25831, "text": " Approach #1 : Naive Approach" }, { "code": null, "e": 26039, "s": 25861, "text": "The first approach is the naive approach. Use a for loop and traverse through the given list and count the occurrence of each item of tuple in a list. Finally, return the count." }, { "code": "# Python3 Program to count occurrence # of all elements of list in a tuplefrom collections import Counter def countOccurrence(tup, lst): count = 0 for item in tup: if item in lst: count+= 1 return count # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst))", "e": 26375, "s": 26039, "text": null }, { "code": null, "e": 26378, "s": 26375, "text": "3\n" }, { "code": null, "e": 26727, "s": 26378, "text": " Approach #2 : Using CounterFrom Python Collections module, import counter to solve the given problem. A Counter is a container that keeps track of how many times equivalent values are added. Having saved the resultant in ‘counts’, we use a for loop and count how many times each item in list occurs in ‘counts’ and sum it to give the final output." }, { "code": "# Python3 Program to count occurrence # of all elements of list in a tuplefrom collections import Counter def countOccurrence(tup, lst): counts = Counter(tup) return sum(counts[i] for i in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst))", "e": 27026, "s": 26727, "text": null }, { "code": null, "e": 27029, "s": 27026, "text": "3\n" }, { "code": null, "e": 27274, "s": 27029, "text": " Approach #3 : Using SetAnother method of solving the given problem is using set data structure. Simply convert the given list into a set, which removes all duplicates. And now, for each item of list, count its occurrence in tuple and sum them." }, { "code": "# Python3 Program to count occurrence # of all elements of list in a tuple def countOccurrence(tup, lst): lst = set(lst) return sum(1 for x in tup if x in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst))", "e": 27539, "s": 27274, "text": null }, { "code": null, "e": 27542, "s": 27539, "text": "3\n" }, { "code": null, "e": 27751, "s": 27542, "text": " Approach #4 : Using Python dictionaryGet each item of tuple and its frequency as key:value pair in Python dictionary, then using a for loop, for each item of list, count its occurrence in tuple and sum them." }, { "code": "# Python3 Program to count occurrence # of all elements of list in a tuple def countOccurrence(tup, lst): dct = {} for i in tup: if not dct.get(i): dct[i] = 0 dct[i] += 1 return sum(dct.get(i, 0) for i in lst) # Driver Codetup = ('a', 'a', 'c', 'b', 'd')lst = ['a', 'b']print(countOccurrence(tup, lst))", "e": 28094, "s": 27751, "text": null }, { "code": null, "e": 28097, "s": 28094, "text": "3\n" }, { "code": null, "e": 28392, "s": 28097, "text": " Approach #5 : Python numpy.in1d()Python numpy gives us a direct method to find the solution for the given problem, and that is numpy.in1d(). This method test whether each element of a 1-D array is also present in a second array. Since list is also a 1-D array, this method can be applied here." }, { "code": "# Python3 Program to count occurrence # of all elements of list in a tupleimport numpy as np def countOccurrence(tup, lst): return np.in1d(tup, lst).sum() # Driver Codetup = ('a', 'a', 'c', 'b', 'd') lst = ['a', 'b']print(countOccurrence(tup, lst))", "e": 28650, "s": 28392, "text": null }, { "code": null, "e": 28653, "s": 28650, "text": "3\n" }, { "code": null, "e": 28675, "s": 28653, "text": "Python tuple-programs" }, { "code": null, "e": 28682, "s": 28675, "text": "Python" }, { "code": null, "e": 28698, "s": 28682, "text": "Python Programs" }, { "code": null, "e": 28796, "s": 28698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28828, "s": 28796, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28870, "s": 28828, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28912, "s": 28870, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28968, "s": 28912, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28995, "s": 28968, "text": "Python Classes and Objects" }, { "code": null, "e": 29017, "s": 28995, "text": "Defaultdict in Python" }, { "code": null, "e": 29056, "s": 29017, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29102, "s": 29056, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29140, "s": 29102, "text": "Python | Convert a list to dictionary" } ]
Find the maximum sum of Plus shape pattern in a 2-D array - GeeksforGeeks
17 May, 2021 Given a 2-D array of size N*M where, . The task is to find the maximum value achievable by a + shaped pattern. The elements of the array can be negative.The plus(+) shape pattern is formed by taking any element with co-ordinate (x, y) as a center and then expanding it in all four directions(if possible). A plus(+) shape has atleast five elements which are { (x-1, y), (x, y-1), (x, y), (x+1, y), (x, y+1) } i.e. the arms should have length>1 but not necessarily need to have same length.Examples: Input: N = 3, M = 4 1 1 1 1 -6 1 1 -4 1 1 1 1 Output: 0 Here, (x, y)=(2, 3) center of pattern(+). Other four arms are, left arm = (2, 2), right arm = (2, 4), up arm = (1, 3), down arm = (2, 3). Hence sum of all elements are ( 1 + 1 + (-4) + 1 + 1 ) = 0. Input: N = 5, M = 3 1 2 3 -6 1 -4 1 1 1 7 8 9 6 3 2 Output: 31 Approach: This problem is an application of the standard Largest Sum Contiguous Subarray.We quickly pre-compute the maximum contiguous sub-sequence (subarray) sum for each row and column, in 4 directions, namely, Up, Down, Left and Right. This can be done using the standard Maximum contiguous sub-sequence sum of a 1-D array.We make four 2-D array’s 1 for each direction. up[i][j]– Maximum sum contiguous sub-sequence of elements in upward direction, from rows 1, 2, 3, ..., i More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[1][j], arr[2][j], ..., arr[i][j]down[i][j] -Maximum sum contiguous sub-sequence of elements in downward direction, from rows i, i+1, i+2,,..., N More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i+1][j], ..., arr[N][j]left[i][j]– Maximum sum contiguous sub-sequence of elements in left direction, from columns 1, 2, 3, ..., j More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][1], arr[i][2], ..., arr[i][j]right[i][j]– Maximum sum contiguous sub-sequence of elements in right direction, from columns j, j+1, j+2, ..., M More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i][j+1], ..., arr[i][M] up[i][j]– Maximum sum contiguous sub-sequence of elements in upward direction, from rows 1, 2, 3, ..., i More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[1][j], arr[2][j], ..., arr[i][j] down[i][j] -Maximum sum contiguous sub-sequence of elements in downward direction, from rows i, i+1, i+2,,..., N More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i+1][j], ..., arr[N][j] left[i][j]– Maximum sum contiguous sub-sequence of elements in left direction, from columns 1, 2, 3, ..., j More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][1], arr[i][2], ..., arr[i][j] right[i][j]– Maximum sum contiguous sub-sequence of elements in right direction, from columns j, j+1, j+2, ..., M More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i][j+1], ..., arr[i][M] All that’s left is, to check each cell as a possible center of the + and use pre-computed data to find the value achieved by + shape in O(1). Below is the implementation of above approach: C++ Java Python 3 C# Javascript // C++ program to find the maximum value// of a + shaped pattern in 2-D array#include <bits/stdc++.h>using namespace std;#define N 100 const int n = 3, m = 4; // Function to return maximum Plus valueint maxPlus(int (&arr)[n][m]){ // Initializing answer with the minimum value int ans = INT_MIN; // Initializing all four arrays int left[N][N], right[N][N], up[N][N], down[N][N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i][j] = max(0LL, (j ? left[i][j - 1] : 0LL)) + arr[i][j]; up[i][j] = max(0LL, (i ? up[i - 1][j] : 0LL)) + arr[i][j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i][j] = max(0LL, (j + 1 == m ? 0LL: right[i][j + 1])) + arr[i][j]; down[i][j] = max(0LL, (i + 1 == n ? 0LL: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); return ans;} // Driver codeint main(){ int arr[n][m] = { { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value cout << maxPlus(arr); return 0;} // Java program to find the maximum value// of a + shaped pattern in 2-D array class GFG{ public static int N = 100; public static int n = 3, m = 4; // Function to return maximum Plus value public static int maxPlus(int[][] arr) { // Initializing answer with the minimum value int ans = Integer.MIN_VALUE; // Initializing all four arrays int[][] left = new int[N][N]; int[][] right = new int[N][N]; int[][] up = new int[N][N]; int[][] down = new int[N][N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i][j] = Math.max(0, ((j != 0) ? left[i][j - 1] : 0)) + arr[i][j]; up[i][j] = Math.max(0, ((i != 0)? up[i - 1][j] : 0)) + arr[i][j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i][j] = Math.max(0, (j + 1 == m ? 0: right[i][j + 1])) + arr[i][j]; down[i][j] = Math.max(0, (i + 1 == n ? 0: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = Math.max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); return ans; } // Driver code public static void main(String[] args) { int[][] arr = new int[][]{ { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value System.out.println( maxPlus(arr) ); }} // This code is contributed by PrinciRaj1992. # Python 3 program to find the maximum value# of a + shaped pattern in 2-D array N = 100 n = 3m = 4 # Function to return maximum# Plus valuedef maxPlus(arr): # Initializing answer with # the minimum value ans = 0 # Initializing all four arrays left = [[0 for x in range(N)] for y in range(N)] right = [[0 for x in range(N)] for y in range(N)] up = [[0 for x in range(N)] for y in range(N)] down = [[0 for x in range(N)] for y in range(N)] # Initializing left and up array. for i in range(n) : for j in range(m) : left[i][j] = (max(0, (left[i][j - 1] if j else 0)) + arr[i][j]) up[i][j] = (max(0, (up[i - 1][j] if i else 0)) + arr[i][j]) # Initializing right and down array. for i in range(n) : for j in range(m) : right[i][j] = max(0, (0 if (j + 1 == m ) else right[i][j + 1])) + arr[i][j] down[i][j] = max(0, (0 if (i + 1 == n ) else down[i + 1][j])) + arr[i][j] # calculating value of maximum # Plus (+) sign for i in range(1, n - 1): for j in range(1, m - 1): ans = max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]) return ans # Driver codeif __name__ == "__main__": arr = [[ 1, 1, 1, 1 ], [ -6, 1, 1, -4 ], [ 1, 1, 1, 1 ]] # Function call to find maximum value print(maxPlus(arr)) # This code is contributed# by ChitraNayal // C# program to find the maximum value// of a + shaped pattern in 2-D arrayusing System; class GFG{ public static int N = 100; public static int n = 3, m = 4; // Function to return maximum Plus value public static int maxPlus(int[,] arr) { // Initializing answer with the minimum value int ans = int.MinValue; // Initializing all four arrays int[,] left = new int[N,N]; int[,] right = new int[N,N]; int[,] up = new int[N,N]; int[,] down = new int[N,N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i,j] = Math.Max(0, ((j != 0) ? left[i,j - 1] : 0)) + arr[i,j]; up[i,j] = Math.Max(0, ((i != 0)? up[i - 1,j] : 0)) + arr[i,j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i,j] = Math.Max(0, (j + 1 == m ? 0: right[i,j + 1])) + arr[i,j]; down[i,j] = Math.Max(0, (i + 1 == n ? 0: down[i + 1,j])) + arr[i,j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = Math.Max(ans, up[i - 1,j] + down[i + 1,j] + left[i,j - 1] + right[i,j + 1] + arr[i,j]); return ans; } // Driver code static void Main() { int[,] arr = new int[,]{ { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value Console.Write( maxPlus(arr) ); }} // This code is contributed by DrRoot_ <script> // JavaScript program to find the maximum value// of a + shaped pattern in 2-D array let N = 100; let n = 3, m = 4; //Function to return maximum Plus value function maxPlus(arr) { // Initializing answer with the minimum value let ans = 0; // Initializing all four arrays let left = new Array(N); let right = new Array(N); let up = new Array(N); let down = new Array(N); for(let i=0;i<N;i++) { left[i]=new Array(N); right[i]=new Array(N); up[i]=new Array(N); down[i]=new Array(N); for(let j=0;j<N;j++) { left[i][j]=0; right[i][j]=0; up[i][j]=0; down[i][j]=0; } } // Initializing left and up array. for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { left[i][j] = Math.max(0, ((j != 0) ? left[i][j - 1] : 0)) + arr[i][j]; up[i][j] = Math.max(0, ((i != 0)? up[i - 1][j] : 0)) + arr[i][j]; } } // Initializing right and down array. for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { right[i][j] = Math.max(0, (j + 1 == m ? 0: right[i][j + 1])) + arr[i][j]; down[i][j] = Math.max(0, (i + 1 == n ? 0: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (let i = 1; i < n - 1; ++i) for (let j = 1; j < m - 1; ++j) { ans = Math.max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); } return ans; } // Driver code let arr = [[ 1, 1, 1, 1 ], [ -6, 1, 1, -4 ], [ 1, 1, 1, 1 ]]; document.write(maxPlus(arr)); // This code is contributed by avanitrachhadiya2155 </script> 0 Time Complexity: O(N2) ukasp DrRoot_ princiraj1992 avanitrachhadiya2155 Arrays Dynamic Programming Matrix Arrays Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 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": 26067, "s": 26039, "text": "\n17 May, 2021" }, { "code": null, "e": 26568, "s": 26067, "text": "Given a 2-D array of size N*M where, . The task is to find the maximum value achievable by a + shaped pattern. The elements of the array can be negative.The plus(+) shape pattern is formed by taking any element with co-ordinate (x, y) as a center and then expanding it in all four directions(if possible). A plus(+) shape has atleast five elements which are { (x-1, y), (x, y-1), (x, y), (x+1, y), (x, y+1) } i.e. the arms should have length>1 but not necessarily need to have same length.Examples: " }, { "code": null, "e": 26941, "s": 26568, "text": "Input: N = 3, M = 4\n 1 1 1 1\n -6 1 1 -4\n 1 1 1 1\nOutput: 0\nHere, (x, y)=(2, 3) center of pattern(+).\nOther four arms are, left arm = (2, 2), right arm = (2, 4), \nup arm = (1, 3), down arm = (2, 3).\nHence sum of all elements are ( 1 + 1 + (-4) + 1 + 1 ) = 0.\n\nInput: N = 5, M = 3\n 1 2 3\n -6 1 -4\n 1 1 1\n 7 8 9\n 6 3 2\nOutput: 31" }, { "code": null, "e": 27318, "s": 26943, "text": "Approach: This problem is an application of the standard Largest Sum Contiguous Subarray.We quickly pre-compute the maximum contiguous sub-sequence (subarray) sum for each row and column, in 4 directions, namely, Up, Down, Left and Right. This can be done using the standard Maximum contiguous sub-sequence sum of a 1-D array.We make four 2-D array’s 1 for each direction. " }, { "code": null, "e": 28367, "s": 27318, "text": "up[i][j]– Maximum sum contiguous sub-sequence of elements in upward direction, from rows 1, 2, 3, ..., i More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[1][j], arr[2][j], ..., arr[i][j]down[i][j] -Maximum sum contiguous sub-sequence of elements in downward direction, from rows i, i+1, i+2,,..., N More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i+1][j], ..., arr[N][j]left[i][j]– Maximum sum contiguous sub-sequence of elements in left direction, from columns 1, 2, 3, ..., j More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][1], arr[i][2], ..., arr[i][j]right[i][j]– Maximum sum contiguous sub-sequence of elements in right direction, from columns j, j+1, j+2, ..., M More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i][j+1], ..., arr[i][M]" }, { "code": null, "e": 28624, "s": 28367, "text": "up[i][j]– Maximum sum contiguous sub-sequence of elements in upward direction, from rows 1, 2, 3, ..., i More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[1][j], arr[2][j], ..., arr[i][j]" }, { "code": null, "e": 28891, "s": 28624, "text": "down[i][j] -Maximum sum contiguous sub-sequence of elements in downward direction, from rows i, i+1, i+2,,..., N More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i+1][j], ..., arr[N][j]" }, { "code": null, "e": 29151, "s": 28891, "text": "left[i][j]– Maximum sum contiguous sub-sequence of elements in left direction, from columns 1, 2, 3, ..., j More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][1], arr[i][2], ..., arr[i][j]" }, { "code": null, "e": 29419, "s": 29151, "text": "right[i][j]– Maximum sum contiguous sub-sequence of elements in right direction, from columns j, j+1, j+2, ..., M More formally, it represents the maximum sum obtained by adding a contiguous sub-sequence of elements from list of arr[i][j], arr[i][j+1], ..., arr[i][M]" }, { "code": null, "e": 29609, "s": 29419, "text": "All that’s left is, to check each cell as a possible center of the + and use pre-computed data to find the value achieved by + shape in O(1). Below is the implementation of above approach: " }, { "code": null, "e": 29613, "s": 29609, "text": "C++" }, { "code": null, "e": 29618, "s": 29613, "text": "Java" }, { "code": null, "e": 29627, "s": 29618, "text": "Python 3" }, { "code": null, "e": 29630, "s": 29627, "text": "C#" }, { "code": null, "e": 29641, "s": 29630, "text": "Javascript" }, { "code": "// C++ program to find the maximum value// of a + shaped pattern in 2-D array#include <bits/stdc++.h>using namespace std;#define N 100 const int n = 3, m = 4; // Function to return maximum Plus valueint maxPlus(int (&arr)[n][m]){ // Initializing answer with the minimum value int ans = INT_MIN; // Initializing all four arrays int left[N][N], right[N][N], up[N][N], down[N][N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i][j] = max(0LL, (j ? left[i][j - 1] : 0LL)) + arr[i][j]; up[i][j] = max(0LL, (i ? up[i - 1][j] : 0LL)) + arr[i][j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i][j] = max(0LL, (j + 1 == m ? 0LL: right[i][j + 1])) + arr[i][j]; down[i][j] = max(0LL, (i + 1 == n ? 0LL: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); return ans;} // Driver codeint main(){ int arr[n][m] = { { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value cout << maxPlus(arr); return 0;}", "e": 31294, "s": 29641, "text": null }, { "code": "// Java program to find the maximum value// of a + shaped pattern in 2-D array class GFG{ public static int N = 100; public static int n = 3, m = 4; // Function to return maximum Plus value public static int maxPlus(int[][] arr) { // Initializing answer with the minimum value int ans = Integer.MIN_VALUE; // Initializing all four arrays int[][] left = new int[N][N]; int[][] right = new int[N][N]; int[][] up = new int[N][N]; int[][] down = new int[N][N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i][j] = Math.max(0, ((j != 0) ? left[i][j - 1] : 0)) + arr[i][j]; up[i][j] = Math.max(0, ((i != 0)? up[i - 1][j] : 0)) + arr[i][j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i][j] = Math.max(0, (j + 1 == m ? 0: right[i][j + 1])) + arr[i][j]; down[i][j] = Math.max(0, (i + 1 == n ? 0: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = Math.max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); return ans; } // Driver code public static void main(String[] args) { int[][] arr = new int[][]{ { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value System.out.println( maxPlus(arr) ); }} // This code is contributed by PrinciRaj1992.", "e": 33439, "s": 31294, "text": null }, { "code": "# Python 3 program to find the maximum value# of a + shaped pattern in 2-D array N = 100 n = 3m = 4 # Function to return maximum# Plus valuedef maxPlus(arr): # Initializing answer with # the minimum value ans = 0 # Initializing all four arrays left = [[0 for x in range(N)] for y in range(N)] right = [[0 for x in range(N)] for y in range(N)] up = [[0 for x in range(N)] for y in range(N)] down = [[0 for x in range(N)] for y in range(N)] # Initializing left and up array. for i in range(n) : for j in range(m) : left[i][j] = (max(0, (left[i][j - 1] if j else 0)) + arr[i][j]) up[i][j] = (max(0, (up[i - 1][j] if i else 0)) + arr[i][j]) # Initializing right and down array. for i in range(n) : for j in range(m) : right[i][j] = max(0, (0 if (j + 1 == m ) else right[i][j + 1])) + arr[i][j] down[i][j] = max(0, (0 if (i + 1 == n ) else down[i + 1][j])) + arr[i][j] # calculating value of maximum # Plus (+) sign for i in range(1, n - 1): for j in range(1, m - 1): ans = max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]) return ans # Driver codeif __name__ == \"__main__\": arr = [[ 1, 1, 1, 1 ], [ -6, 1, 1, -4 ], [ 1, 1, 1, 1 ]] # Function call to find maximum value print(maxPlus(arr)) # This code is contributed# by ChitraNayal", "e": 35091, "s": 33439, "text": null }, { "code": "// C# program to find the maximum value// of a + shaped pattern in 2-D arrayusing System; class GFG{ public static int N = 100; public static int n = 3, m = 4; // Function to return maximum Plus value public static int maxPlus(int[,] arr) { // Initializing answer with the minimum value int ans = int.MinValue; // Initializing all four arrays int[,] left = new int[N,N]; int[,] right = new int[N,N]; int[,] up = new int[N,N]; int[,] down = new int[N,N]; // Initializing left and up array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { left[i,j] = Math.Max(0, ((j != 0) ? left[i,j - 1] : 0)) + arr[i,j]; up[i,j] = Math.Max(0, ((i != 0)? up[i - 1,j] : 0)) + arr[i,j]; } } // Initializing right and down array. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { right[i,j] = Math.Max(0, (j + 1 == m ? 0: right[i,j + 1])) + arr[i,j]; down[i,j] = Math.Max(0, (i + 1 == n ? 0: down[i + 1,j])) + arr[i,j]; } } // calculating value of maximum Plus (+) sign for (int i = 1; i < n - 1; ++i) for (int j = 1; j < m - 1; ++j) ans = Math.Max(ans, up[i - 1,j] + down[i + 1,j] + left[i,j - 1] + right[i,j + 1] + arr[i,j]); return ans; } // Driver code static void Main() { int[,] arr = new int[,]{ { 1, 1, 1, 1 }, { -6, 1, 1, -4 }, { 1, 1, 1, 1 } }; // Function call to find maximum value Console.Write( maxPlus(arr) ); }} // This code is contributed by DrRoot_", "e": 37112, "s": 35091, "text": null }, { "code": "<script> // JavaScript program to find the maximum value// of a + shaped pattern in 2-D array let N = 100; let n = 3, m = 4; //Function to return maximum Plus value function maxPlus(arr) { // Initializing answer with the minimum value let ans = 0; // Initializing all four arrays let left = new Array(N); let right = new Array(N); let up = new Array(N); let down = new Array(N); for(let i=0;i<N;i++) { left[i]=new Array(N); right[i]=new Array(N); up[i]=new Array(N); down[i]=new Array(N); for(let j=0;j<N;j++) { left[i][j]=0; right[i][j]=0; up[i][j]=0; down[i][j]=0; } } // Initializing left and up array. for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { left[i][j] = Math.max(0, ((j != 0) ? left[i][j - 1] : 0)) + arr[i][j]; up[i][j] = Math.max(0, ((i != 0)? up[i - 1][j] : 0)) + arr[i][j]; } } // Initializing right and down array. for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { right[i][j] = Math.max(0, (j + 1 == m ? 0: right[i][j + 1])) + arr[i][j]; down[i][j] = Math.max(0, (i + 1 == n ? 0: down[i + 1][j])) + arr[i][j]; } } // calculating value of maximum Plus (+) sign for (let i = 1; i < n - 1; ++i) for (let j = 1; j < m - 1; ++j) { ans = Math.max(ans, up[i - 1][j] + down[i + 1][j] + left[i][j - 1] + right[i][j + 1] + arr[i][j]); } return ans; } // Driver code let arr = [[ 1, 1, 1, 1 ], [ -6, 1, 1, -4 ], [ 1, 1, 1, 1 ]]; document.write(maxPlus(arr)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 39341, "s": 37112, "text": null }, { "code": null, "e": 39343, "s": 39341, "text": "0" }, { "code": null, "e": 39369, "s": 39345, "text": "Time Complexity: O(N2) " }, { "code": null, "e": 39375, "s": 39369, "text": "ukasp" }, { "code": null, "e": 39383, "s": 39375, "text": "DrRoot_" }, { "code": null, "e": 39397, "s": 39383, "text": "princiraj1992" }, { "code": null, "e": 39418, "s": 39397, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39425, "s": 39418, "text": "Arrays" }, { "code": null, "e": 39445, "s": 39425, "text": "Dynamic Programming" }, { "code": null, "e": 39452, "s": 39445, "text": "Matrix" }, { "code": null, "e": 39459, "s": 39452, "text": "Arrays" }, { "code": null, "e": 39479, "s": 39459, "text": "Dynamic Programming" }, { "code": null, "e": 39486, "s": 39479, "text": "Matrix" }, { "code": null, "e": 39584, "s": 39486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39611, "s": 39584, "text": "Count pairs with given sum" }, { "code": null, "e": 39642, "s": 39611, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 39667, "s": 39642, "text": "Window Sliding Technique" }, { "code": null, "e": 39705, "s": 39667, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39726, "s": 39705, "text": "Next Greater Element" }, { "code": null, "e": 39755, "s": 39726, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 39785, "s": 39755, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39819, "s": 39785, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 39850, "s": 39819, "text": "Bellman–Ford Algorithm | DP-23" } ]
Difference between Dilation and Erosion - GeeksforGeeks
12 Aug, 2021 Dilation and Erosion are basic morphological processing operations that produce contrasting results when applied to either gray-scale or binary images. Dilation: Dilation is the reverse process with regions growing out from their boundaries.Dilation is A XOR B. Dilation is A XOR B. Erosion: Erosion involves the removal of pixels ate the edges of the region.Erosion is just the dual of Dilation. Erosion is just the dual of Dilation. Both dilation and erosion are produced by the interaction of s set called a structuring element(SE). Difference between Dilation and Erosion: varshagumber28 MATLAB Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6 Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Difference between SQL and NoSQL Logical and Physical Address in Operating System Difference between DDL and DML in DBMS Difference between Prim's and Kruskal's algorithm for MST Difference between Primary Key and Foreign Key
[ { "code": null, "e": 26240, "s": 26212, "text": "\n12 Aug, 2021" }, { "code": null, "e": 26392, "s": 26240, "text": "Dilation and Erosion are basic morphological processing operations that produce contrasting results when applied to either gray-scale or binary images." }, { "code": null, "e": 26502, "s": 26392, "text": "Dilation: Dilation is the reverse process with regions growing out from their boundaries.Dilation is A XOR B." }, { "code": null, "e": 26523, "s": 26502, "text": "Dilation is A XOR B." }, { "code": null, "e": 26637, "s": 26523, "text": "Erosion: Erosion involves the removal of pixels ate the edges of the region.Erosion is just the dual of Dilation." }, { "code": null, "e": 26675, "s": 26637, "text": "Erosion is just the dual of Dilation." }, { "code": null, "e": 26777, "s": 26675, "text": "Both dilation and erosion are produced by the interaction of s set called a structuring element(SE). " }, { "code": null, "e": 26820, "s": 26777, "text": "Difference between Dilation and Erosion: " }, { "code": null, "e": 26835, "s": 26820, "text": "varshagumber28" }, { "code": null, "e": 26842, "s": 26835, "text": "MATLAB" }, { "code": null, "e": 26861, "s": 26842, "text": "Difference Between" }, { "code": null, "e": 26959, "s": 26861, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27020, "s": 26959, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27054, "s": 27020, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 27122, "s": 27054, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27160, "s": 27122, "text": "Difference between Process and Thread" }, { "code": null, "e": 27213, "s": 27160, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27246, "s": 27213, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 27295, "s": 27246, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27334, "s": 27295, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27392, "s": 27334, "text": "Difference between Prim's and Kruskal's algorithm for MST" } ]
How to Use Different Row Methods to Get Number of Rows in a Table in JDBC? - GeeksforGeeks
18 Nov, 2021 Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for specific databases. Types of DatabaseSQLMySQL: mysql-connector-java-8.0.22PostgreSQLOracle: ojdbc14.jarMicrosoft SQL serverNoSQLMongoDB: mongo-java-driver-3.12.7BigTableRedisProgressCassandraCouchDBRavenDB SQLMySQL: mysql-connector-java-8.0.22PostgreSQLOracle: ojdbc14.jarMicrosoft SQL server MySQL: mysql-connector-java-8.0.22 PostgreSQL Oracle: ojdbc14.jar Microsoft SQL server NoSQLMongoDB: mongo-java-driver-3.12.7BigTableRedisProgressCassandraCouchDBRavenDB MongoDB: mongo-java-driver-3.12.7 BigTable Redis Progress Cassandra CouchDB RavenDB Illustration: SQL and Oracle databases are mostly used for illustration. Here SQL database is taken into consideration. Here Table_Name is Table name. Here it will take all columns and count the rows. Input: Existing data in the table is shown in the below image SQL server used: sqljdbc4.jar SQL table used CREATE TABLE `studentsdetails` ( `id` int(6) unsigned NOT NULL, `Name` varchar(50) NOT NULL, `caste` varchar(10) NOT NULL, `NeetMarks` int(11) NOT NULL, `gender` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Approaches: A less efficient way of creating a query select count(*) from Table_Name; A more efficient way of creating a query select count(1) from Table_Name; This query will take the first column and count the rows. As mostly, the Primary key is the first column, it is ideal enough as the Primary key is always unique and not null. Example 1: To get the number of rows in a table in JDBC by selecting count(1) from ‘studentsdetails’ will provide the result as 5. Java /* Java Program to use different row methodsto get no of rows in a table in JDBC */ // Step 1: Importing database librariesimport java.sql.*; // Only main class- GFG is shown// connection class object is usedpublic class GFG { // Main driver method public static void main(String[] args) { // Initially connection is assigned Null valued Connection con = null; ResultSet res = null; // Try block to check exceptions try { /* Step 2: Load and register drivers or relevant jars in build path of project */ // Here- 'mysql-connector-java-8.0.22' // is used using Class.forNmae() method Class.forName("com.mysql.cj.jdbc.Driver"); /* Step 3: Establish a connection using DriverManager method */ con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", ""); // Try block to check exceptions try { Statement st = con.createStatement(); /* This query will take first column and count the rows. As mostly, Primary key is the first column, it is ideal enough as Primary key is always unique and not null */ /* Step 4: Create a statement */ /* Alias name is used as NumberOfRows for COUNT(1) Moving the cursor to the last row */ res = st.executeQuery( "SELECT COUNT(1) as NumberOfRows FROM " + "studentsdetails"); /* Step 5: Execute the query */ res.next(); /* Step 6: Process the results */ System.out.println( "MySQL Table - studentsdetails contains " + res.getInt("NumberOfRows") + " rows"); } // Catch block to handle exceptions catch (SQLException s) { // Message to be displayed if SQLException // occurs System.out.println( "SQL statement is not executed!"); } } catch (Exception e) { /* Displaying line where exception occured using method returning line number in code */ e.printStackTrace(); } finally { // Step 7: Closing the connection res = null; con = null; } }} Output: Example 2: To get the number of rows in a table in JDBC Java /* Step 1: Importing Database libraries */import java.sql.*; /* Only main class-GFG is shownConnection class of JDBC is not shown.Object of connection class is used */public class GFG { // Main driver method public static void main(String[] args) { /* Objects are assigned null before any execution */ // Connection class objects Connection con = null; ResultSet res = null; // Try block to check exceptions try { /* Step 2: Load and register drivers or relevant jars in build path of project */ // Driver used- 'mysql-connector-java-8.0.22' // Loading and register drivers // using Class.forname() method Class.forName("com.mysql.cj.jdbc.Driver"); /* Step 3: Create a connection */ // using DriverManager con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", ""); // Display message when connection // is successfully established System.out.println( "Connection is established"); // Try block to check exceptions try { /* In order to avoid Result set type is TYPE_FORWARD_ONLY */ Statement st = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); /* Query takes first column and count the rows. As mostly, Primary key is the first column, it is ideal enough as Primary key is always unique & not null. */ /* Step 4: Creating the statement */ res = st.executeQuery("SELECT * FROM " + "studentsdetails"); /* Step 5: Execute the statements */ // Moving the cursor to the last row res.last(); /* Step 6: Process the results */ System.out.println( "MySQL Table - studentsdetails contains " + res.getRow() + " rows"); } // Catch block to handle exceptions catch (SQLException s) { // Exception handled if it is SQL based System.out.println( "SQL statement is not executed!" + s.getMessage()); } } catch (Exception e) { // Exception handled here if it is generic // program based e.printStackTrace(); } finally { // Step 7: Closing the connection res = null; con = null; } }} Output: adnanirshad158 akshaysingh98088 anikaseth98 surindertarika1234 sweetyty prachisoda1234 JDBC Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n18 Nov, 2021" }, { "code": null, "e": 25544, "s": 25225, "text": "Java supports many databases and for each database, we need to have their respective jar files to be placed in the build path to proceed for JDBC connectivity. For different databases, different jar files are imported to make a connection given below or their built path is supposed to be added for specific databases." }, { "code": null, "e": 25730, "s": 25544, "text": "Types of DatabaseSQLMySQL: mysql-connector-java-8.0.22PostgreSQLOracle: ojdbc14.jarMicrosoft SQL serverNoSQLMongoDB: mongo-java-driver-3.12.7BigTableRedisProgressCassandraCouchDBRavenDB" }, { "code": null, "e": 25817, "s": 25730, "text": "SQLMySQL: mysql-connector-java-8.0.22PostgreSQLOracle: ojdbc14.jarMicrosoft SQL server" }, { "code": null, "e": 25852, "s": 25817, "text": "MySQL: mysql-connector-java-8.0.22" }, { "code": null, "e": 25863, "s": 25852, "text": "PostgreSQL" }, { "code": null, "e": 25883, "s": 25863, "text": "Oracle: ojdbc14.jar" }, { "code": null, "e": 25904, "s": 25883, "text": "Microsoft SQL server" }, { "code": null, "e": 25987, "s": 25904, "text": "NoSQLMongoDB: mongo-java-driver-3.12.7BigTableRedisProgressCassandraCouchDBRavenDB" }, { "code": null, "e": 26021, "s": 25987, "text": "MongoDB: mongo-java-driver-3.12.7" }, { "code": null, "e": 26030, "s": 26021, "text": "BigTable" }, { "code": null, "e": 26036, "s": 26030, "text": "Redis" }, { "code": null, "e": 26045, "s": 26036, "text": "Progress" }, { "code": null, "e": 26055, "s": 26045, "text": "Cassandra" }, { "code": null, "e": 26063, "s": 26055, "text": "CouchDB" }, { "code": null, "e": 26071, "s": 26063, "text": "RavenDB" }, { "code": null, "e": 26272, "s": 26071, "text": "Illustration: SQL and Oracle databases are mostly used for illustration. Here SQL database is taken into consideration. Here Table_Name is Table name. Here it will take all columns and count the rows." }, { "code": null, "e": 26334, "s": 26272, "text": "Input: Existing data in the table is shown in the below image" }, { "code": null, "e": 26364, "s": 26334, "text": "SQL server used: sqljdbc4.jar" }, { "code": null, "e": 26379, "s": 26364, "text": "SQL table used" }, { "code": null, "e": 26626, "s": 26379, "text": "CREATE TABLE `studentsdetails` (\n`id` int(6) unsigned NOT NULL,\n`Name` varchar(50) NOT NULL,\n`caste` varchar(10) NOT NULL,\n`NeetMarks` int(11) NOT NULL,\n`gender` varchar(10) DEFAULT NULL,\nPRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;" }, { "code": null, "e": 26639, "s": 26626, "text": "Approaches: " }, { "code": null, "e": 26680, "s": 26639, "text": "A less efficient way of creating a query" }, { "code": null, "e": 26713, "s": 26680, "text": "select count(*) from Table_Name;" }, { "code": null, "e": 26754, "s": 26713, "text": "A more efficient way of creating a query" }, { "code": null, "e": 26787, "s": 26754, "text": "select count(1) from Table_Name;" }, { "code": null, "e": 26962, "s": 26787, "text": "This query will take the first column and count the rows. As mostly, the Primary key is the first column, it is ideal enough as the Primary key is always unique and not null." }, { "code": null, "e": 27093, "s": 26962, "text": "Example 1: To get the number of rows in a table in JDBC by selecting count(1) from ‘studentsdetails’ will provide the result as 5." }, { "code": null, "e": 27098, "s": 27093, "text": "Java" }, { "code": "/* Java Program to use different row methodsto get no of rows in a table in JDBC */ // Step 1: Importing database librariesimport java.sql.*; // Only main class- GFG is shown// connection class object is usedpublic class GFG { // Main driver method public static void main(String[] args) { // Initially connection is assigned Null valued Connection con = null; ResultSet res = null; // Try block to check exceptions try { /* Step 2: Load and register drivers or relevant jars in build path of project */ // Here- 'mysql-connector-java-8.0.22' // is used using Class.forNmae() method Class.forName(\"com.mysql.cj.jdbc.Driver\"); /* Step 3: Establish a connection using DriverManager method */ con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/test?serverTimezone=UTC\", \"root\", \"\"); // Try block to check exceptions try { Statement st = con.createStatement(); /* This query will take first column and count the rows. As mostly, Primary key is the first column, it is ideal enough as Primary key is always unique and not null */ /* Step 4: Create a statement */ /* Alias name is used as NumberOfRows for COUNT(1) Moving the cursor to the last row */ res = st.executeQuery( \"SELECT COUNT(1) as NumberOfRows FROM \" + \"studentsdetails\"); /* Step 5: Execute the query */ res.next(); /* Step 6: Process the results */ System.out.println( \"MySQL Table - studentsdetails contains \" + res.getInt(\"NumberOfRows\") + \" rows\"); } // Catch block to handle exceptions catch (SQLException s) { // Message to be displayed if SQLException // occurs System.out.println( \"SQL statement is not executed!\"); } } catch (Exception e) { /* Displaying line where exception occured using method returning line number in code */ e.printStackTrace(); } finally { // Step 7: Closing the connection res = null; con = null; } }}", "e": 29639, "s": 27098, "text": null }, { "code": null, "e": 29649, "s": 29639, "text": " Output: " }, { "code": null, "e": 29705, "s": 29649, "text": "Example 2: To get the number of rows in a table in JDBC" }, { "code": null, "e": 29710, "s": 29705, "text": "Java" }, { "code": "/* Step 1: Importing Database libraries */import java.sql.*; /* Only main class-GFG is shownConnection class of JDBC is not shown.Object of connection class is used */public class GFG { // Main driver method public static void main(String[] args) { /* Objects are assigned null before any execution */ // Connection class objects Connection con = null; ResultSet res = null; // Try block to check exceptions try { /* Step 2: Load and register drivers or relevant jars in build path of project */ // Driver used- 'mysql-connector-java-8.0.22' // Loading and register drivers // using Class.forname() method Class.forName(\"com.mysql.cj.jdbc.Driver\"); /* Step 3: Create a connection */ // using DriverManager con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/test?serverTimezone=UTC\", \"root\", \"\"); // Display message when connection // is successfully established System.out.println( \"Connection is established\"); // Try block to check exceptions try { /* In order to avoid Result set type is TYPE_FORWARD_ONLY */ Statement st = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); /* Query takes first column and count the rows. As mostly, Primary key is the first column, it is ideal enough as Primary key is always unique & not null. */ /* Step 4: Creating the statement */ res = st.executeQuery(\"SELECT * FROM \" + \"studentsdetails\"); /* Step 5: Execute the statements */ // Moving the cursor to the last row res.last(); /* Step 6: Process the results */ System.out.println( \"MySQL Table - studentsdetails contains \" + res.getRow() + \" rows\"); } // Catch block to handle exceptions catch (SQLException s) { // Exception handled if it is SQL based System.out.println( \"SQL statement is not executed!\" + s.getMessage()); } } catch (Exception e) { // Exception handled here if it is generic // program based e.printStackTrace(); } finally { // Step 7: Closing the connection res = null; con = null; } }}", "e": 32495, "s": 29710, "text": null }, { "code": null, "e": 32504, "s": 32495, "text": "Output: " }, { "code": null, "e": 32519, "s": 32504, "text": "adnanirshad158" }, { "code": null, "e": 32536, "s": 32519, "text": "akshaysingh98088" }, { "code": null, "e": 32548, "s": 32536, "text": "anikaseth98" }, { "code": null, "e": 32567, "s": 32548, "text": "surindertarika1234" }, { "code": null, "e": 32576, "s": 32567, "text": "sweetyty" }, { "code": null, "e": 32591, "s": 32576, "text": "prachisoda1234" }, { "code": null, "e": 32596, "s": 32591, "text": "JDBC" }, { "code": null, "e": 32603, "s": 32596, "text": "Picked" }, { "code": null, "e": 32627, "s": 32603, "text": "Technical Scripter 2020" }, { "code": null, "e": 32632, "s": 32627, "text": "Java" }, { "code": null, "e": 32646, "s": 32632, "text": "Java Programs" }, { "code": null, "e": 32665, "s": 32646, "text": "Technical Scripter" }, { "code": null, "e": 32670, "s": 32665, "text": "Java" }, { "code": null, "e": 32768, "s": 32670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32783, "s": 32768, "text": "Stream In Java" }, { "code": null, "e": 32804, "s": 32783, "text": "Constructors in Java" }, { "code": null, "e": 32823, "s": 32804, "text": "Exceptions in Java" }, { "code": null, "e": 32853, "s": 32823, "text": "Functional Interfaces in Java" }, { "code": null, "e": 32899, "s": 32853, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32925, "s": 32899, "text": "Java Programming Examples" }, { "code": null, "e": 32959, "s": 32925, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 33006, "s": 32959, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 33038, "s": 33006, "text": "How to Iterate HashMap in Java?" } ]
How to set ASCII Characters in MaskedTextBox in C#? - GeeksforGeeks
26 Jul, 2019 In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to insert ASCII or non-ASCII(arbitrary Unicode characters) characters in the MaskedTextBox using AsciiOnly Property.If the value of this property is true, then you can insert ASCII characters in the MaskedTextBox and if the value of this property is false, then you can insert characters other than ASCII characters. The default value of this property is false. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the value of AsciiOnly property of MaskedTextBox control as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of AsciiOnly property of MaskedTextBox control as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of AsciiOnly property of the MaskedTextBox control programmatically with the help of given syntax: public bool AsciiOnly { get; set; } The value of this property is of System.Boolean type, either true or false. The following steps show how to set the value of AsciiOnly property of the MaskedTextBox control dynamically: Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); // Creating a MaskedTextBox MaskedTextBox m = new MaskedTextBox(); Step 2: After creating MaskedTextBox, set the AsciiOnly property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the AsciiOnly property m.AsciiOnly = false; // Setting the AsciiOnly property m.AsciiOnly = false; Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form this.Controls.Add(m); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.AsciiOnly = false; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output: // Adding MaskedTextBox control on the form this.Controls.Add(m); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = " Example"; l1.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = "Phone number:"; l2.Font = new Font("Bell MT", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = "000000000"; m.Size = new Size(176, 20); m.Name = "MyBox"; m.BorderStyle = BorderStyle.Fixed3D; m.AsciiOnly = false; m.Font = new Font("Bell MT", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Switch Statement in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n26 Jul, 2019" }, { "code": null, "e": 26229, "s": 25547, "text": "In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input. In MaskedTextBox control, you are allowed to insert ASCII or non-ASCII(arbitrary Unicode characters) characters in the MaskedTextBox using AsciiOnly Property.If the value of this property is true, then you can insert ASCII characters in the MaskedTextBox and if the value of this property is false, then you can insert characters other than ASCII characters. The default value of this property is false. You can set this property in two different ways:" }, { "code": null, "e": 26364, "s": 26229, "text": "1. Design-Time: It is the easiest way to set the value of AsciiOnly property of MaskedTextBox control as shown in the following steps:" }, { "code": null, "e": 26480, "s": 26364, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26592, "s": 26480, "text": "Step 2: Next, drag and drop the MaskedTextBox control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 26772, "s": 26592, "text": "Step 3: After drag and drop you will go to the properties of the MaskedTextBox and set the value of AsciiOnly property of MaskedTextBox control as shown in the below image:Output:" }, { "code": null, "e": 26780, "s": 26772, "text": "Output:" }, { "code": null, "e": 26981, "s": 26780, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the value of AsciiOnly property of the MaskedTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 27017, "s": 26981, "text": "public bool AsciiOnly { get; set; }" }, { "code": null, "e": 27203, "s": 27017, "text": "The value of this property is of System.Boolean type, either true or false. The following steps show how to set the value of AsciiOnly property of the MaskedTextBox control dynamically:" }, { "code": null, "e": 27379, "s": 27203, "text": "Step 1: Create a MaskedTextBox using the MaskedTextBox() constructor is provided by the MaskedTextBox class.// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 27447, "s": 27379, "text": "// Creating a MaskedTextBox\nMaskedTextBox m = new MaskedTextBox();\n" }, { "code": null, "e": 27625, "s": 27447, "text": "Step 2: After creating MaskedTextBox, set the AsciiOnly property of the MaskedTextBox provided by the MaskedTextBox class.// Setting the AsciiOnly property\nm.AsciiOnly = false;\n" }, { "code": null, "e": 27681, "s": 27625, "text": "// Setting the AsciiOnly property\nm.AsciiOnly = false;\n" }, { "code": null, "e": 29357, "s": 27681, "text": "Step 3: And last add this MaskedTextBox control to the form using the following statement:// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.AsciiOnly = false; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}Output:" }, { "code": null, "e": 29424, "s": 29357, "text": "// Adding MaskedTextBox control on the form\nthis.Controls.Add(m);\n" }, { "code": null, "e": 29433, "s": 29424, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp39 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label l1 = new Label(); l1.Location = new Point(413, 98); l1.Size = new Size(176, 20); l1.Text = \" Example\"; l1.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l1); // Creating and setting the // properties of the Label Label l2 = new Label(); l2.Location = new Point(242, 135); l2.Size = new Size(126, 20); l2.Text = \"Phone number:\"; l2.Font = new Font(\"Bell MT\", 12); // Adding label on the form this.Controls.Add(l2); // Creating and setting the // properties of the MaskedTextBox MaskedTextBox m = new MaskedTextBox(); m.Location = new Point(374, 137); m.Mask = \"000000000\"; m.Size = new Size(176, 20); m.Name = \"MyBox\"; m.BorderStyle = BorderStyle.Fixed3D; m.AsciiOnly = false; m.Font = new Font(\"Bell MT\", 18); // Adding MaskedTextBox // control on the form this.Controls.Add(m); }}}", "e": 30938, "s": 29433, "text": null }, { "code": null, "e": 30946, "s": 30938, "text": "Output:" }, { "code": null, "e": 30977, "s": 30946, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 30980, "s": 30977, "text": "C#" }, { "code": null, "e": 31078, "s": 30980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31101, "s": 31078, "text": "Extension Method in C#" }, { "code": null, "e": 31129, "s": 31101, "text": "HashSet in C# with Examples" }, { "code": null, "e": 31146, "s": 31129, "text": "C# | Inheritance" }, { "code": null, "e": 31168, "s": 31146, "text": "Partial Classes in C#" }, { "code": null, "e": 31197, "s": 31168, "text": "C# | Generics - Introduction" }, { "code": null, "e": 31237, "s": 31197, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 31280, "s": 31237, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 31303, "s": 31280, "text": "Switch Statement in C#" }, { "code": null, "e": 31336, "s": 31303, "text": "Linked List Implementation in C#" } ]
Introduction to Programming Languages - GeeksforGeeks
31 Aug, 2021 Are you aiming to become a software engineer one day? Do you also want to develop a mobile application that people all over the world would love to use? Are you passionate enough to take the big step to enter the world of programming? Then you are in the right place because through this article you will get a brief introduction to programming. Now before we understand what programming is, you must know what is a computer. A computer is a device that can accept human instruction, processes it, and responds to it or a computer is a computational device that is used to process the data under the control of a computer program. Program is a sequence of instruction along with data. The basic components of a computer are: Input unitCentral Processing Unit(CPU)Output unit Input unit Central Processing Unit(CPU) Output unit The CPU is further divided into three parts- Memory unit Control unit Arithmetic Logic unit Most of us have heard that CPU is called the brain of our computer because it accepts data, provides temporary memory space to it until it is stored(saved) on the hard disk, performs logical operations on it and hence processes(here also means converts) data into information. We all know that a computer consists of hardware and software. Software is a set of programs that performs multiple tasks together. An operating system is also software (system software) that helps humans to interact with the computer system. A program is a set of instructions given to a computer to perform a specific operation. or computer is a computational device that is used to process the data under the control of a computer program. While executing the program, raw data is processed into the desired output format. These computer programs are written in a programming language which are high-level languages. High level languages are nearly human languages that are more complex than the computer understandable language which are called machine language, or low level language. So after knowing the basics, we are ready to create a very simple and basic program. Like we have different languages to communicate with each other, likewise, we have different languages like C, C++, C#, Java, python, etc to communicate with the computers. The computer only understands binary language (the language of 0’s and 1’s) also called machine-understandable language or low-level language but the programs we are going to write are in a high-level language which is almost similar to human language. The piece of code given below performs a basic task of printing “hello world! I am learning programming” on the console screen. We must know that keyboard, scanner, mouse, microphone, etc are various examples of input devices, and monitor(console screen), printer, speaker, etc are examples of output devices. main() { clrscr(); printf(“hello world! I am learning to program"); getch(); } At this stage, you might not be able to understand in-depth how this code prints something on the screen. The main() is a standard function that you will always include in any program that you are going to create from now onwards. Note that the execution of the program starts from the main() function. The clrscr() function is used to see only the current output on the screen while the printf() function helps us to print the desired output on the screen. Also, getch() is a function that accepts any character input from the keyboard. In simple words, we need to press any key to continue(some people may say that getch() helps in holding the screen to see the output). Between high-level language and machine language, there are assembly languages also called symbolic machine code. Assembly languages are particularly computer architecture specific. Utility program (Assembler) is used to convert assembly code into executable machine code. High Level Programming Language is portable but requires Interpretation or compiling to convert it into a machine language that is computer understood. Hierarchy of Computer language – There have been many programming languages some of them are listed below: Most Popular Programming Languages – C Python C++ Java SCALA C# R Ruby Go Swift JavaScript Characteristics of a programming Language – A programming language must be simple, easy to learn and use, have good readability, and be human recognizable. Abstraction is a must-have Characteristics for a programming language in which the ability to define the complex structure and then its degree of usability comes. A portable programming language is always preferred. Programming language’s efficiency must be high so that it can be easily converted into a machine code and executed consumes little space in memory. A programming language should be well structured and documented so that it is suitable for application development. Necessary tools for the development, debugging, testing, maintenance of a program must be provided by a programming language. A programming language should provide a single environment known as Integrated Development Environment(IDE). A programming language must be consistent in terms of syntax and semantics. khushipuri37 sanskaromar01 school-programming Articles Competitive Programming GBlog Misc Programming Language Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis) SQL Interview Questions Understanding "extern" keyword in C Mutex vs Semaphore Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25777, "s": 25749, "text": "\n31 Aug, 2021" }, { "code": null, "e": 26463, "s": 25777, "text": "Are you aiming to become a software engineer one day? Do you also want to develop a mobile application that people all over the world would love to use? Are you passionate enough to take the big step to enter the world of programming? Then you are in the right place because through this article you will get a brief introduction to programming. Now before we understand what programming is, you must know what is a computer. A computer is a device that can accept human instruction, processes it, and responds to it or a computer is a computational device that is used to process the data under the control of a computer program. Program is a sequence of instruction along with data. " }, { "code": null, "e": 26504, "s": 26463, "text": "The basic components of a computer are: " }, { "code": null, "e": 26554, "s": 26504, "text": "Input unitCentral Processing Unit(CPU)Output unit" }, { "code": null, "e": 26565, "s": 26554, "text": "Input unit" }, { "code": null, "e": 26594, "s": 26565, "text": "Central Processing Unit(CPU)" }, { "code": null, "e": 26606, "s": 26594, "text": "Output unit" }, { "code": null, "e": 26653, "s": 26606, "text": "The CPU is further divided into three parts- " }, { "code": null, "e": 26665, "s": 26653, "text": "Memory unit" }, { "code": null, "e": 26678, "s": 26665, "text": "Control unit" }, { "code": null, "e": 26700, "s": 26678, "text": "Arithmetic Logic unit" }, { "code": null, "e": 27221, "s": 26700, "text": "Most of us have heard that CPU is called the brain of our computer because it accepts data, provides temporary memory space to it until it is stored(saved) on the hard disk, performs logical operations on it and hence processes(here also means converts) data into information. We all know that a computer consists of hardware and software. Software is a set of programs that performs multiple tasks together. An operating system is also software (system software) that helps humans to interact with the computer system. " }, { "code": null, "e": 28280, "s": 27221, "text": "A program is a set of instructions given to a computer to perform a specific operation. or computer is a computational device that is used to process the data under the control of a computer program. While executing the program, raw data is processed into the desired output format. These computer programs are written in a programming language which are high-level languages. High level languages are nearly human languages that are more complex than the computer understandable language which are called machine language, or low level language. So after knowing the basics, we are ready to create a very simple and basic program. Like we have different languages to communicate with each other, likewise, we have different languages like C, C++, C#, Java, python, etc to communicate with the computers. The computer only understands binary language (the language of 0’s and 1’s) also called machine-understandable language or low-level language but the programs we are going to write are in a high-level language which is almost similar to human language. " }, { "code": null, "e": 28591, "s": 28280, "text": "The piece of code given below performs a basic task of printing “hello world! I am learning programming” on the console screen. We must know that keyboard, scanner, mouse, microphone, etc are various examples of input devices, and monitor(console screen), printer, speaker, etc are examples of output devices. " }, { "code": null, "e": 28676, "s": 28591, "text": "main()\n {\n clrscr();\n printf(“hello world! I am learning to program\");\n getch();\n } " }, { "code": null, "e": 29350, "s": 28676, "text": "At this stage, you might not be able to understand in-depth how this code prints something on the screen. The main() is a standard function that you will always include in any program that you are going to create from now onwards. Note that the execution of the program starts from the main() function. The clrscr() function is used to see only the current output on the screen while the printf() function helps us to print the desired output on the screen. Also, getch() is a function that accepts any character input from the keyboard. In simple words, we need to press any key to continue(some people may say that getch() helps in holding the screen to see the output). " }, { "code": null, "e": 29776, "s": 29350, "text": "Between high-level language and machine language, there are assembly languages also called symbolic machine code. Assembly languages are particularly computer architecture specific. Utility program (Assembler) is used to convert assembly code into executable machine code. High Level Programming Language is portable but requires Interpretation or compiling to convert it into a machine language that is computer understood. " }, { "code": null, "e": 29810, "s": 29776, "text": "Hierarchy of Computer language – " }, { "code": null, "e": 29885, "s": 29810, "text": "There have been many programming languages some of them are listed below: " }, { "code": null, "e": 29924, "s": 29885, "text": "Most Popular Programming Languages – " }, { "code": null, "e": 29926, "s": 29924, "text": "C" }, { "code": null, "e": 29933, "s": 29926, "text": "Python" }, { "code": null, "e": 29937, "s": 29933, "text": "C++" }, { "code": null, "e": 29942, "s": 29937, "text": "Java" }, { "code": null, "e": 29948, "s": 29942, "text": "SCALA" }, { "code": null, "e": 29951, "s": 29948, "text": "C#" }, { "code": null, "e": 29953, "s": 29951, "text": "R" }, { "code": null, "e": 29958, "s": 29953, "text": "Ruby" }, { "code": null, "e": 29961, "s": 29958, "text": "Go" }, { "code": null, "e": 29967, "s": 29961, "text": "Swift" }, { "code": null, "e": 29978, "s": 29967, "text": "JavaScript" }, { "code": null, "e": 30023, "s": 29978, "text": "Characteristics of a programming Language – " }, { "code": null, "e": 30135, "s": 30023, "text": "A programming language must be simple, easy to learn and use, have good readability, and be human recognizable." }, { "code": null, "e": 30298, "s": 30135, "text": "Abstraction is a must-have Characteristics for a programming language in which the ability to define the complex structure and then its degree of usability comes." }, { "code": null, "e": 30351, "s": 30298, "text": "A portable programming language is always preferred." }, { "code": null, "e": 30499, "s": 30351, "text": "Programming language’s efficiency must be high so that it can be easily converted into a machine code and executed consumes little space in memory." }, { "code": null, "e": 30615, "s": 30499, "text": "A programming language should be well structured and documented so that it is suitable for application development." }, { "code": null, "e": 30741, "s": 30615, "text": "Necessary tools for the development, debugging, testing, maintenance of a program must be provided by a programming language." }, { "code": null, "e": 30850, "s": 30741, "text": "A programming language should provide a single environment known as Integrated Development Environment(IDE)." }, { "code": null, "e": 30926, "s": 30850, "text": "A programming language must be consistent in terms of syntax and semantics." }, { "code": null, "e": 30939, "s": 30926, "text": "khushipuri37" }, { "code": null, "e": 30953, "s": 30939, "text": "sanskaromar01" }, { "code": null, "e": 30972, "s": 30953, "text": "school-programming" }, { "code": null, "e": 30981, "s": 30972, "text": "Articles" }, { "code": null, "e": 31005, "s": 30981, "text": "Competitive Programming" }, { "code": null, "e": 31011, "s": 31005, "text": "GBlog" }, { "code": null, "e": 31016, "s": 31011, "text": "Misc" }, { "code": null, "e": 31037, "s": 31016, "text": "Programming Language" }, { "code": null, "e": 31042, "s": 31037, "text": "Misc" }, { "code": null, "e": 31047, "s": 31042, "text": "Misc" }, { "code": null, "e": 31145, "s": 31047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31173, "s": 31145, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 31226, "s": 31173, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 31250, "s": 31226, "text": "SQL Interview Questions" }, { "code": null, "e": 31286, "s": 31250, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 31305, "s": 31286, "text": "Mutex vs Semaphore" }, { "code": null, "e": 31348, "s": 31305, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31391, "s": 31348, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31432, "s": 31391, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31510, "s": 31432, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Removing spaces from a string using Stringstream - GeeksforGeeks
13 Aug, 2021 Solution to removing spaces from a string is already posted here. In this article another solution using stringstream is discussed. Algorithm: 1. Enter the whole string into stringstream. 2. Empty the string. 3. Extract word by word and concatenate to the string. Program 1: Using EOF. CPP // C++ program to remove spaces using stringstream#include <bits/stdc++.h>using namespace std; // Function to remove spacesstring removeSpaces(string str){ stringstream ss; string temp; // Storing the whole string // into string stream ss << str; // Making the string empty str = ""; // Running loop till end of stream while (!ss.eof()) { // Extracting word by word from stream ss >> temp; // Concatenating in the string to be // returned str = str + temp; } return str;} // Driver functionint main(){ // Sample Inputs string s = "This is a test"; cout << removeSpaces(s) << endl; s = "geeks for geeks"; cout << removeSpaces(s) << endl; s = "geeks quiz is awesome!"; cout << removeSpaces(s) << endl; s = "I love to code"; cout << removeSpaces(s) << endl; return 0;} Thisisatest geeksforgeeks geeksquizisawesome! Ilovetocode Program 2: Using getline(). CPP // C++ program to remove spaces using stringstream// and getline()#include <bits/stdc++.h>using namespace std; // Function to remove spacesstring removeSpaces(string str){ // Storing the whole string // into string stream stringstream ss(str); string temp; // Making the string empty str = ""; // Running loop till end of stream // and getting every word while (getline(ss, temp, ' ')) { // Concatenating in the string // to be returned str = str + temp; } return str;}// Driver functionint main(){ // Sample Inputs string s = "This is a test"; cout << removeSpaces(s) << endl; s = "geeks for geeks"; cout << removeSpaces(s) << endl; s = "geeks quiz is awesome!"; cout << removeSpaces(s) << endl; s = "I love to code"; cout << removeSpaces(s) << endl; return 0;} // Code contributed by saychakr13 Thisisatest geeksforgeeks geeksquizisawesome! Ilovetocode This article is contributed by Nishant. 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. saychakr13 akshaysingh98088 cpp-string cpp-stringstream C Language C++ Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25887, "s": 25859, "text": "\n13 Aug, 2021" }, { "code": null, "e": 26020, "s": 25887, "text": "Solution to removing spaces from a string is already posted here. In this article another solution using stringstream is discussed. " }, { "code": null, "e": 26032, "s": 26020, "text": "Algorithm: " }, { "code": null, "e": 26153, "s": 26032, "text": "1. Enter the whole string into stringstream.\n2. Empty the string.\n3. Extract word by word and concatenate to the string." }, { "code": null, "e": 26176, "s": 26153, "text": "Program 1: Using EOF. " }, { "code": null, "e": 26180, "s": 26176, "text": "CPP" }, { "code": "// C++ program to remove spaces using stringstream#include <bits/stdc++.h>using namespace std; // Function to remove spacesstring removeSpaces(string str){ stringstream ss; string temp; // Storing the whole string // into string stream ss << str; // Making the string empty str = \"\"; // Running loop till end of stream while (!ss.eof()) { // Extracting word by word from stream ss >> temp; // Concatenating in the string to be // returned str = str + temp; } return str;} // Driver functionint main(){ // Sample Inputs string s = \"This is a test\"; cout << removeSpaces(s) << endl; s = \"geeks for geeks\"; cout << removeSpaces(s) << endl; s = \"geeks quiz is awesome!\"; cout << removeSpaces(s) << endl; s = \"I love to code\"; cout << removeSpaces(s) << endl; return 0;}", "e": 27061, "s": 26180, "text": null }, { "code": null, "e": 27119, "s": 27061, "text": "Thisisatest\ngeeksforgeeks\ngeeksquizisawesome!\nIlovetocode" }, { "code": null, "e": 27148, "s": 27119, "text": "Program 2: Using getline(). " }, { "code": null, "e": 27152, "s": 27148, "text": "CPP" }, { "code": "// C++ program to remove spaces using stringstream// and getline()#include <bits/stdc++.h>using namespace std; // Function to remove spacesstring removeSpaces(string str){ // Storing the whole string // into string stream stringstream ss(str); string temp; // Making the string empty str = \"\"; // Running loop till end of stream // and getting every word while (getline(ss, temp, ' ')) { // Concatenating in the string // to be returned str = str + temp; } return str;}// Driver functionint main(){ // Sample Inputs string s = \"This is a test\"; cout << removeSpaces(s) << endl; s = \"geeks for geeks\"; cout << removeSpaces(s) << endl; s = \"geeks quiz is awesome!\"; cout << removeSpaces(s) << endl; s = \"I love to code\"; cout << removeSpaces(s) << endl; return 0;} // Code contributed by saychakr13", "e": 28049, "s": 27152, "text": null }, { "code": null, "e": 28107, "s": 28049, "text": "Thisisatest\ngeeksforgeeks\ngeeksquizisawesome!\nIlovetocode" }, { "code": null, "e": 28522, "s": 28107, "text": "This article is contributed by Nishant. 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": 28533, "s": 28522, "text": "saychakr13" }, { "code": null, "e": 28550, "s": 28533, "text": "akshaysingh98088" }, { "code": null, "e": 28561, "s": 28550, "text": "cpp-string" }, { "code": null, "e": 28578, "s": 28561, "text": "cpp-stringstream" }, { "code": null, "e": 28589, "s": 28578, "text": "C Language" }, { "code": null, "e": 28593, "s": 28589, "text": "C++" }, { "code": null, "e": 28601, "s": 28593, "text": "Strings" }, { "code": null, "e": 28609, "s": 28601, "text": "Strings" }, { "code": null, "e": 28613, "s": 28609, "text": "CPP" }, { "code": null, "e": 28711, "s": 28613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28728, "s": 28711, "text": "Substring in C++" }, { "code": null, "e": 28763, "s": 28728, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 28809, "s": 28763, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 28831, "s": 28809, "text": "Function Pointer in C" }, { "code": null, "e": 28871, "s": 28831, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 28889, "s": 28871, "text": "Vector in C++ STL" }, { "code": null, "e": 28935, "s": 28889, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28954, "s": 28935, "text": "Inheritance in C++" }, { "code": null, "e": 28997, "s": 28954, "text": "Map in C++ Standard Template Library (STL)" } ]
jQuery | select() with Examples - GeeksforGeeks
13 Feb, 2019 The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field. Syntax: $(selector).select(function); Parameter: This method accepts single parameter function which is optional. Th function parameter will run after select method call. Return Value: This method returns a notification when something is select. Below example illustrates the select() method in jQuery: Example: <!DOCTYPE html><html> <head> <title>Select Method</title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- JQuery code to show the working of this method --> <script> $(document).ready(function() { $("input").select(function() { alert("Something was selected"); }); }); </script> <style> div { width: 250px; height: 40px; padding: 20px; border: 2px solid green; } </style> </head> <body> <div> <!-- select any thing from inside this field --> <input type="text" value="GeeksforGeeks!"> </div> </body></html> Output:Before select anything !After selecting some letters or words ! jQuery-Events JavaScript JQuery 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? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 26606, "s": 26578, "text": "\n13 Feb, 2019" }, { "code": null, "e": 26755, "s": 26606, "text": "The select() method is an inbuilt method in jQuery which is used when some letters or words are selected (or marked) in a text area or a text field." }, { "code": null, "e": 26763, "s": 26755, "text": "Syntax:" }, { "code": null, "e": 26793, "s": 26763, "text": "$(selector).select(function);" }, { "code": null, "e": 26926, "s": 26793, "text": "Parameter: This method accepts single parameter function which is optional. Th function parameter will run after select method call." }, { "code": null, "e": 27001, "s": 26926, "text": "Return Value: This method returns a notification when something is select." }, { "code": null, "e": 27058, "s": 27001, "text": "Below example illustrates the select() method in jQuery:" }, { "code": null, "e": 27067, "s": 27058, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Select Method</title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- JQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"input\").select(function() { alert(\"Something was selected\"); }); }); </script> <style> div { width: 250px; height: 40px; padding: 20px; border: 2px solid green; } </style> </head> <body> <div> <!-- select any thing from inside this field --> <input type=\"text\" value=\"GeeksforGeeks!\"> </div> </body></html>", "e": 27896, "s": 27067, "text": null }, { "code": null, "e": 27967, "s": 27896, "text": "Output:Before select anything !After selecting some letters or words !" }, { "code": null, "e": 27981, "s": 27967, "text": "jQuery-Events" }, { "code": null, "e": 27992, "s": 27981, "text": "JavaScript" }, { "code": null, "e": 27999, "s": 27992, "text": "JQuery" }, { "code": null, "e": 28097, "s": 27999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28137, "s": 28097, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28198, "s": 28137, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28239, "s": 28198, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28261, "s": 28239, "text": "JavaScript | Promises" }, { "code": null, "e": 28315, "s": 28261, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28361, "s": 28315, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28390, "s": 28361, "text": "Form validation using jQuery" }, { "code": null, "e": 28453, "s": 28390, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 28527, "s": 28453, "text": "How to fetch data from JSON file and display in HTML table using jQuery ?" } ]
Python | Pandas MultiIndex.swaplevel() - GeeksforGeeks
24 Dec, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas MultiIndex.swaplevel() function is used to swap levels of the MultiIndex. It swap level i with level j. Calling this method does not change the ordering of the values. Syntax: MultiIndex.swaplevel(i=-2, j=-1) Parameters :i : First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.j : Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. Returns : A new MultiIndex Example #1: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex. # importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx) Output : Now let’s swap the 0th level with the 1st level of the MultiIndex. # swap the levelsmidx.swaplevel(0, 1) Output :As we can see in the output, the function has swapped the 0th level with the 1st level of the MultiIndex. Example #2: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex. # importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Beagle', 'Sephard', 'Labrador', 'Retriever'], [8, 4, 11, 3], ['A1', 'B1', 'A2', 'C1']]) # Print the MultiIndexprint(midx) Output : Now let’s swap the 0th level with the 2nd level of the MultiIndex. # swap the levelsmidx.swaplevel(0, 2) Output :As we can see in the output, the function has swapped the 0th level with the 2nd level of the MultiIndex. Python pandas-multiIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python sum() function in Python
[ { "code": null, "e": 26163, "s": 26135, "text": "\n24 Dec, 2018" }, { "code": null, "e": 26377, "s": 26163, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26552, "s": 26377, "text": "Pandas MultiIndex.swaplevel() function is used to swap levels of the MultiIndex. It swap level i with level j. Calling this method does not change the ordering of the values." }, { "code": null, "e": 26593, "s": 26552, "text": "Syntax: MultiIndex.swaplevel(i=-2, j=-1)" }, { "code": null, "e": 26813, "s": 26593, "text": "Parameters :i : First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed.j : Second level of index to be swapped. Can pass level name as string. Type of parameters can be mixed." }, { "code": null, "e": 26840, "s": 26813, "text": "Returns : A new MultiIndex" }, { "code": null, "e": 26948, "s": 26840, "text": "Example #1: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex." }, { "code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography', 'Anthropology', 'Science'], [88, 84, 98, 95]]) # Print the MultiIndexprint(midx)", "e": 27245, "s": 26948, "text": null }, { "code": null, "e": 27254, "s": 27245, "text": "Output :" }, { "code": null, "e": 27321, "s": 27254, "text": "Now let’s swap the 0th level with the 1st level of the MultiIndex." }, { "code": "# swap the levelsmidx.swaplevel(0, 1)", "e": 27359, "s": 27321, "text": null }, { "code": null, "e": 27581, "s": 27359, "text": "Output :As we can see in the output, the function has swapped the 0th level with the 1st level of the MultiIndex. Example #2: Use MultiIndex.swaplevel() function to swap the 0th level with the 1st level of the MultiIndex." }, { "code": "# importing pandas as pdimport pandas as pd # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Beagle', 'Sephard', 'Labrador', 'Retriever'], [8, 4, 11, 3], ['A1', 'B1', 'A2', 'C1']]) # Print the MultiIndexprint(midx)", "e": 27846, "s": 27581, "text": null }, { "code": null, "e": 27855, "s": 27846, "text": "Output :" }, { "code": null, "e": 27922, "s": 27855, "text": "Now let’s swap the 0th level with the 2nd level of the MultiIndex." }, { "code": "# swap the levelsmidx.swaplevel(0, 2)", "e": 27960, "s": 27922, "text": null }, { "code": null, "e": 28074, "s": 27960, "text": "Output :As we can see in the output, the function has swapped the 0th level with the 2nd level of the MultiIndex." }, { "code": null, "e": 28099, "s": 28074, "text": "Python pandas-multiIndex" }, { "code": null, "e": 28113, "s": 28099, "text": "Python-pandas" }, { "code": null, "e": 28120, "s": 28113, "text": "Python" }, { "code": null, "e": 28218, "s": 28120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28236, "s": 28218, "text": "Python Dictionary" }, { "code": null, "e": 28268, "s": 28236, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28290, "s": 28268, "text": "Enumerate() in Python" }, { "code": null, "e": 28332, "s": 28290, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28361, "s": 28332, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28405, "s": 28361, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28442, "s": 28405, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28478, "s": 28442, "text": "Convert integer to string in Python" }, { "code": null, "e": 28520, "s": 28478, "text": "Check if element exists in list in Python" } ]
C# | Convert.ToBase64String() Method | Set-1 - GeeksforGeeks
03 Apr, 2019 Convert.ToBase64String() Method is used to convert the value of an array of 8-bit unsigned integers to its equivalent string representation which is encoded with base-64 digits. There are 4 methods in the overload of this method which are as follows: ToBase64String(Byte[], Int32, Int32) Method ToBase64String(Byte[], Int32, Int32, Base64FormattingOptions) Method ToBase64String(Byte[], Base64FormattingOptions) Method ToBase64String(Byte[]) Method Here, we will discuss only the first method. ToBase64String(Byte[], Int32, Int32) Method is used to convert a subset of an array of 8-bit unsigned integers to its equivalent string representation which is encoded with base-64 digits. Parameters specify the subset as an offset in the input array, and the number of elements in the array to convert. Syntax: public static string ToBase64String (byte[] inArray, int offset, int length); Parameters: inArray: It is an array of 8-bit unsigned integers. offset: It is an offset in inArray. length: It is the number of elements of inArray to convert. Return Value: This method returns the string representation in base 64 of length elements of inArray, starting at position offset. Exceptions: ArgumentNullException: If inArray is null. ArgumentOutOfRangeException: If the offset or length is negative OR offset plus length is greater than the length of inArray. Below programs illustrate the use of Convert.ToBase64String(Byte[], Int32, Int32) Method: Example 1: // C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 and byte2 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; byte[] byte2 = {10, 20, 30, 40, 50}; // calling get() Method get(byte1, "byte1"); Console.WriteLine(""); get(byte2, "byte2"); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine("For {0}", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine("converted string: {0}", val);}} For byte1 converted string: AgQGCAoMDhASFA== For byte2 converted string: ChQeKDI= Example 2: For ArgumentNullException // C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // calling get() Method get(byte1, "byte1"); Console.WriteLine(""); // converting base 64 string // to byte array Console.WriteLine("bye array is null"); string val = Convert.ToBase64String(null, 0, 10); Console.WriteLine("Converted byte value: {0}", val); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine("For {0}", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine("converted string: {0}", val);}} For byte1 converted string: AgQGCAoMDhASFA== bye array is null Exception Thrown: System.ArgumentNullException Example 3: For ArgumentOutOfRangeException // C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // calling get() Method get(byte1, "byte1"); Console.WriteLine(""); // converting base 64 string to byte array Console.WriteLine("Length is negative"); string val = Convert.ToBase64String(byte1, 0, -10); Console.WriteLine("Converted byte value: {0}", val); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine("For {0}", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine("converted string: {0}", val);}} For byte1 converted string: AgQGCAoMDhASFA== Length is negative Exception Thrown: System.ArgumentOutOfRangeException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobase64string?view=netframework-4.7.2#System_Convert_ToBase64String_System_Byte___System_Int32_System_Int32_ CSharp Convert Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n03 Apr, 2019" }, { "code": null, "e": 25798, "s": 25547, "text": "Convert.ToBase64String() Method is used to convert the value of an array of 8-bit unsigned integers to its equivalent string representation which is encoded with base-64 digits. There are 4 methods in the overload of this method which are as follows:" }, { "code": null, "e": 25842, "s": 25798, "text": "ToBase64String(Byte[], Int32, Int32) Method" }, { "code": null, "e": 25911, "s": 25842, "text": "ToBase64String(Byte[], Int32, Int32, Base64FormattingOptions) Method" }, { "code": null, "e": 25966, "s": 25911, "text": "ToBase64String(Byte[], Base64FormattingOptions) Method" }, { "code": null, "e": 25996, "s": 25966, "text": "ToBase64String(Byte[]) Method" }, { "code": null, "e": 26041, "s": 25996, "text": "Here, we will discuss only the first method." }, { "code": null, "e": 26345, "s": 26041, "text": "ToBase64String(Byte[], Int32, Int32) Method is used to convert a subset of an array of 8-bit unsigned integers to its equivalent string representation which is encoded with base-64 digits. Parameters specify the subset as an offset in the input array, and the number of elements in the array to convert." }, { "code": null, "e": 26353, "s": 26345, "text": "Syntax:" }, { "code": null, "e": 26431, "s": 26353, "text": "public static string ToBase64String (byte[] inArray, int offset, int length);" }, { "code": null, "e": 26443, "s": 26431, "text": "Parameters:" }, { "code": null, "e": 26495, "s": 26443, "text": "inArray: It is an array of 8-bit unsigned integers." }, { "code": null, "e": 26531, "s": 26495, "text": "offset: It is an offset in inArray." }, { "code": null, "e": 26591, "s": 26531, "text": "length: It is the number of elements of inArray to convert." }, { "code": null, "e": 26722, "s": 26591, "text": "Return Value: This method returns the string representation in base 64 of length elements of inArray, starting at position offset." }, { "code": null, "e": 26734, "s": 26722, "text": "Exceptions:" }, { "code": null, "e": 26777, "s": 26734, "text": "ArgumentNullException: If inArray is null." }, { "code": null, "e": 26903, "s": 26777, "text": "ArgumentOutOfRangeException: If the offset or length is negative OR offset plus length is greater than the length of inArray." }, { "code": null, "e": 26993, "s": 26903, "text": "Below programs illustrate the use of Convert.ToBase64String(Byte[], Int32, Int32) Method:" }, { "code": null, "e": 27004, "s": 26993, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 and byte2 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; byte[] byte2 = {10, 20, 30, 40, 50}; // calling get() Method get(byte1, \"byte1\"); Console.WriteLine(\"\"); get(byte2, \"byte2\"); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine(\"For {0}\", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine(\"converted string: {0}\", val);}}", "e": 28112, "s": 27004, "text": null }, { "code": null, "e": 28196, "s": 28112, "text": "For byte1\nconverted string: AgQGCAoMDhASFA==\n\nFor byte2\nconverted string: ChQeKDI=\n" }, { "code": null, "e": 28233, "s": 28196, "text": "Example 2: For ArgumentNullException" }, { "code": "// C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // calling get() Method get(byte1, \"byte1\"); Console.WriteLine(\"\"); // converting base 64 string // to byte array Console.WriteLine(\"bye array is null\"); string val = Convert.ToBase64String(null, 0, 10); Console.WriteLine(\"Converted byte value: {0}\", val); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine(\"For {0}\", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine(\"converted string: {0}\", val);}}", "e": 29487, "s": 28233, "text": null }, { "code": null, "e": 29599, "s": 29487, "text": "For byte1\nconverted string: AgQGCAoMDhASFA==\n\nbye array is null\nException Thrown: System.ArgumentNullException\n" }, { "code": null, "e": 29642, "s": 29599, "text": "Example 3: For ArgumentOutOfRangeException" }, { "code": "// C# program to demonstrate the// Convert.ToBase64String() Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // defining and initializing // byte1 byte[] byte1 = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; // calling get() Method get(byte1, \"byte1\"); Console.WriteLine(\"\"); // converting base 64 string to byte array Console.WriteLine(\"Length is negative\"); string val = Convert.ToBase64String(byte1, 0, -10); Console.WriteLine(\"Converted byte value: {0}\", val); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(byte[] bytes, string str){ Console.WriteLine(\"For {0}\", str); // converting byte to base 64 string string val = Convert.ToBase64String(bytes, 0, bytes.Length); // display the converted string Console.WriteLine(\"converted string: {0}\", val);}}", "e": 30897, "s": 29642, "text": null }, { "code": null, "e": 31016, "s": 30897, "text": "For byte1\nconverted string: AgQGCAoMDhASFA==\n\nLength is negative\nException Thrown: System.ArgumentOutOfRangeException\n" }, { "code": null, "e": 31027, "s": 31016, "text": "Reference:" }, { "code": null, "e": 31196, "s": 31027, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobase64string?view=netframework-4.7.2#System_Convert_ToBase64String_System_Byte___System_Int32_System_Int32_" }, { "code": null, "e": 31217, "s": 31196, "text": "CSharp Convert Class" }, { "code": null, "e": 31231, "s": 31217, "text": "CSharp-method" }, { "code": null, "e": 31234, "s": 31231, "text": "C#" }, { "code": null, "e": 31332, "s": 31234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31355, "s": 31332, "text": "Extension Method in C#" }, { "code": null, "e": 31383, "s": 31355, "text": "HashSet in C# with Examples" }, { "code": null, "e": 31400, "s": 31383, "text": "C# | Inheritance" }, { "code": null, "e": 31422, "s": 31400, "text": "Partial Classes in C#" }, { "code": null, "e": 31451, "s": 31422, "text": "C# | Generics - Introduction" }, { "code": null, "e": 31491, "s": 31451, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 31514, "s": 31491, "text": "Switch Statement in C#" }, { "code": null, "e": 31554, "s": 31514, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 31597, "s": 31554, "text": "C# | How to insert an element in an Array?" } ]
Number of strings that satisfy the given condition - GeeksforGeeks
02 Jun, 2021 Given N strings of equal lengths. The strings contain only digits (1 to 9). The task is to count the number of strings that have an index position such that the digit at this index position is greater than the digits at same index position of all the other strings.Examples: Input: arr[] = {“223”, “232”, “112”} Output: 2 First digit of 1st and 2nd strings are the largest. Second digit of the string 2nd is the largest. Third digit of the string 1st is the largest.Input: arr[] = {“999”, “122”, “111”} Output: 1 Approach: For each index position, find the maximal digit in that position across all the strings. And store the indices of the string that satisfy the given condition in a set so that the same string isn’t counted twice for different index positions. Finally, return the size of the set.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of valid stringsint countStrings(int n, int m, string s[]){ // Set to store indices of valid strings unordered_set<int> ind; for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = max(mx, (int)s[i][j] - '0'); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i][j] - '0' == mx) ind.insert(i); } // Return number of strings in the set return ind.size();} // Driver codeint main(){ string s[] = { "223", "232", "112" }; int m = s[0].length(); int n = sizeof(s) / sizeof(s[0]); cout << countStrings(n, m, s);} // Java implementation of the approachimport java.util.*; class GfG{ // Function to return the count of valid stringsstatic int countStrings(int n, int m, String s[]){ // Set to store indices of valid strings HashSet<Integer> ind = new HashSet<Integer>(); for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = Math.max(mx, (int)(s[i].charAt(j) - '0')); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i].charAt(j) - '0' == mx) ind.add(i); } // Return number of strings in the set return ind.size();} // Driver codepublic static void main(String[] args){ String s[] = { "223", "232", "112" }; int m = s[0].length(); int n = s.length; System.out.println(countStrings(n, m, s));}} // This code has been contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the count of# valid stringsdef countStrings(n, m, s): # Set to store indices of # valid strings ind = dict() for j in range(m): mx = 0 str1 = s[j] # Find the maximum digit for # current position for i in range(n): mx = max(mx, int(str1[i])) # Add indices of all the strings in # the set that contain maximal digit for i in range(n): if int(str1[i]) == mx: ind[i] = 1 # Return number of strings # in the set return len(ind) # Driver codes = ["223", "232", "112"]m = len(s[0])n = len(s)print(countStrings(n, m, s)) # This code is contributed# by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function to return the count of valid stringsstatic int countStrings(int n, int m, String[] s){ // Set to store indices of valid strings HashSet<int> ind = new HashSet<int>(); for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = Math.Max(mx, (int)(s[i][j] - '0')); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i][j] - '0' == mx) ind.Add(i); } // Return number of strings in the set return ind.Count;} // Driver codepublic static void Main(){ String []s = { "223", "232", "112" }; int m = s[0].Length; int n = s.Length; Console.WriteLine(countStrings(n, m, s));}} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript implementation of the approach // Function to return the count of valid stringsfunction countStrings(n,m,s){ // Set to store indices of valid strings let ind = new Set(); for (let j = 0; j < m; j++) { let mx = 0; // Find the maximum digit for current position for (let i = 0; i < n; i++) mx = Math.max(mx, (s[i][j].charCodeAt(0) - '0'.charCodeAt(0))); // Add indices of all the strings in the set // that contain maximal digit for (let i = 0; i < n; i++) if (s[i][j].charCodeAt(0) - '0'.charCodeAt(0) == mx) ind.add(i); } // Return number of strings in the set return ind.size;} // Driver codelet s=[ "223", "232", "112"];let m = s[0].length;let n = s.length;document.write(countStrings(n, m, s)); // This code is contributed by patel2127 </script> 2 Time Complexity: O(N * M) where N is the number of strings and M is the length of the strings. mohit kumar 29 29AjayKumar princiraj1992 patel2127 cpp-unordered_set Competitive Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming 5 Best Languages for Competitive Programming Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26281, "s": 26253, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26558, "s": 26281, "text": "Given N strings of equal lengths. The strings contain only digits (1 to 9). The task is to count the number of strings that have an index position such that the digit at this index position is greater than the digits at same index position of all the other strings.Examples: " }, { "code": null, "e": 26798, "s": 26558, "text": "Input: arr[] = {“223”, “232”, “112”} Output: 2 First digit of 1st and 2nd strings are the largest. Second digit of the string 2nd is the largest. Third digit of the string 1st is the largest.Input: arr[] = {“999”, “122”, “111”} Output: 1 " }, { "code": null, "e": 27141, "s": 26800, "text": "Approach: For each index position, find the maximal digit in that position across all the strings. And store the indices of the string that satisfy the given condition in a set so that the same string isn’t counted twice for different index positions. Finally, return the size of the set.Below is the implementation of the above approach: " }, { "code": null, "e": 27145, "s": 27141, "text": "C++" }, { "code": null, "e": 27150, "s": 27145, "text": "Java" }, { "code": null, "e": 27158, "s": 27150, "text": "Python3" }, { "code": null, "e": 27161, "s": 27158, "text": "C#" }, { "code": null, "e": 27172, "s": 27161, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of valid stringsint countStrings(int n, int m, string s[]){ // Set to store indices of valid strings unordered_set<int> ind; for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = max(mx, (int)s[i][j] - '0'); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i][j] - '0' == mx) ind.insert(i); } // Return number of strings in the set return ind.size();} // Driver codeint main(){ string s[] = { \"223\", \"232\", \"112\" }; int m = s[0].length(); int n = sizeof(s) / sizeof(s[0]); cout << countStrings(n, m, s);}", "e": 28032, "s": 27172, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GfG{ // Function to return the count of valid stringsstatic int countStrings(int n, int m, String s[]){ // Set to store indices of valid strings HashSet<Integer> ind = new HashSet<Integer>(); for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = Math.max(mx, (int)(s[i].charAt(j) - '0')); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i].charAt(j) - '0' == mx) ind.add(i); } // Return number of strings in the set return ind.size();} // Driver codepublic static void main(String[] args){ String s[] = { \"223\", \"232\", \"112\" }; int m = s[0].length(); int n = s.length; System.out.println(countStrings(n, m, s));}} // This code has been contributed by 29AjayKumar", "e": 29004, "s": 28032, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of# valid stringsdef countStrings(n, m, s): # Set to store indices of # valid strings ind = dict() for j in range(m): mx = 0 str1 = s[j] # Find the maximum digit for # current position for i in range(n): mx = max(mx, int(str1[i])) # Add indices of all the strings in # the set that contain maximal digit for i in range(n): if int(str1[i]) == mx: ind[i] = 1 # Return number of strings # in the set return len(ind) # Driver codes = [\"223\", \"232\", \"112\"]m = len(s[0])n = len(s)print(countStrings(n, m, s)) # This code is contributed# by Mohit Kumar", "e": 29745, "s": 29004, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function to return the count of valid stringsstatic int countStrings(int n, int m, String[] s){ // Set to store indices of valid strings HashSet<int> ind = new HashSet<int>(); for (int j = 0; j < m; j++) { int mx = 0; // Find the maximum digit for current position for (int i = 0; i < n; i++) mx = Math.Max(mx, (int)(s[i][j] - '0')); // Add indices of all the strings in the set // that contain maximal digit for (int i = 0; i < n; i++) if (s[i][j] - '0' == mx) ind.Add(i); } // Return number of strings in the set return ind.Count;} // Driver codepublic static void Main(){ String []s = { \"223\", \"232\", \"112\" }; int m = s[0].Length; int n = s.Length; Console.WriteLine(countStrings(n, m, s));}} /* This code contributed by PrinciRaj1992 */", "e": 30699, "s": 29745, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the count of valid stringsfunction countStrings(n,m,s){ // Set to store indices of valid strings let ind = new Set(); for (let j = 0; j < m; j++) { let mx = 0; // Find the maximum digit for current position for (let i = 0; i < n; i++) mx = Math.max(mx, (s[i][j].charCodeAt(0) - '0'.charCodeAt(0))); // Add indices of all the strings in the set // that contain maximal digit for (let i = 0; i < n; i++) if (s[i][j].charCodeAt(0) - '0'.charCodeAt(0) == mx) ind.add(i); } // Return number of strings in the set return ind.size;} // Driver codelet s=[ \"223\", \"232\", \"112\"];let m = s[0].length;let n = s.length;document.write(countStrings(n, m, s)); // This code is contributed by patel2127 </script>", "e": 31591, "s": 30699, "text": null }, { "code": null, "e": 31593, "s": 31591, "text": "2" }, { "code": null, "e": 31691, "s": 31595, "text": "Time Complexity: O(N * M) where N is the number of strings and M is the length of the strings. " }, { "code": null, "e": 31706, "s": 31691, "text": "mohit kumar 29" }, { "code": null, "e": 31718, "s": 31706, "text": "29AjayKumar" }, { "code": null, "e": 31732, "s": 31718, "text": "princiraj1992" }, { "code": null, "e": 31742, "s": 31732, "text": "patel2127" }, { "code": null, "e": 31760, "s": 31742, "text": "cpp-unordered_set" }, { "code": null, "e": 31784, "s": 31760, "text": "Competitive Programming" }, { "code": null, "e": 31792, "s": 31784, "text": "Strings" }, { "code": null, "e": 31800, "s": 31792, "text": "Strings" }, { "code": null, "e": 31898, "s": 31800, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31931, "s": 31898, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 31977, "s": 31931, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 32035, "s": 31977, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 32076, "s": 32035, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 32121, "s": 32076, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 32167, "s": 32121, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32192, "s": 32167, "text": "Reverse a string in Java" }, { "code": null, "e": 32252, "s": 32192, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32267, "s": 32252, "text": "C++ Data Types" } ]
Replacing column value of a CSV file in Python - GeeksforGeeks
02 Sep, 2020 Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-delimited file. Method 1: Using Native Python way Using replace() method, we can replace easily a text into another text. In the below code, let us have an input CSV file as “csvfile.csv” and be opened in “read” mode. The join() method takes all lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text. Example: The input file will be: Python3 # reading the CSV filetext = open("csvfile.csv", "r") #join() method combines all contents of # csvfile.csv and formed as a stringtext = ''.join([i for i in text]) # search and replace the contentstext = text.replace("EmployeeName", "EmpName") text = text.replace("EmployeeNumber", "EmpNumber") text = text.replace("EmployeeDepartment", "EmpDepartment") text = text.replace("lined", "linked") # output.csv is the output file opened in write modex = open("output.csv","w") # all the replaced text is written in the output.csv filex.writelines(text)x.close() Output: Method 2: Using Pandas DataFrame We can read the CSV file as a DataFrame and then apply the replace() method. Python3 # importing the moduleimport pandas as pd # making data frame from the csv file dataframe = pd.read_csv("csvfile1.csv") # using the replace() methoddataframe.replace(to_replace ="Fashion", value = "Fashion industry", inplace = True)dataframe.replace(to_replace ="Food", value = "Food Industry", inplace = True)dataframe.replace(to_replace ="IT", value = "IT Industry", inplace = True) # writing the dataframe to another csv filedataframe.to_csv('outputfile.csv', index = False) Output: python-csv Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 26230, "s": 26202, "text": "\n02 Sep, 2020" }, { "code": null, "e": 26350, "s": 26230, "text": "Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-delimited file." }, { "code": null, "e": 26385, "s": 26350, "text": "Method 1: Using Native Python way " }, { "code": null, "e": 26837, "s": 26385, "text": "Using replace() method, we can replace easily a text into another text. In the below code, let us have an input CSV file as “csvfile.csv” and be opened in “read” mode. The join() method takes all lines of a CSV file in an iterable and joins them into one string. Then, we can use replace() method on the entire string and can perform single/multiple replacements. In the entire string, the given text is searched and replaced with the specified text." }, { "code": null, "e": 26847, "s": 26837, "text": "Example: " }, { "code": null, "e": 26871, "s": 26847, "text": "The input file will be:" }, { "code": null, "e": 26879, "s": 26871, "text": "Python3" }, { "code": "# reading the CSV filetext = open(\"csvfile.csv\", \"r\") #join() method combines all contents of # csvfile.csv and formed as a stringtext = ''.join([i for i in text]) # search and replace the contentstext = text.replace(\"EmployeeName\", \"EmpName\") text = text.replace(\"EmployeeNumber\", \"EmpNumber\") text = text.replace(\"EmployeeDepartment\", \"EmpDepartment\") text = text.replace(\"lined\", \"linked\") # output.csv is the output file opened in write modex = open(\"output.csv\",\"w\") # all the replaced text is written in the output.csv filex.writelines(text)x.close()", "e": 27442, "s": 26879, "text": null }, { "code": null, "e": 27450, "s": 27442, "text": "Output:" }, { "code": null, "e": 27483, "s": 27450, "text": "Method 2: Using Pandas DataFrame" }, { "code": null, "e": 27560, "s": 27483, "text": "We can read the CSV file as a DataFrame and then apply the replace() method." }, { "code": null, "e": 27568, "s": 27560, "text": "Python3" }, { "code": "# importing the moduleimport pandas as pd # making data frame from the csv file dataframe = pd.read_csv(\"csvfile1.csv\") # using the replace() methoddataframe.replace(to_replace =\"Fashion\", value = \"Fashion industry\", inplace = True)dataframe.replace(to_replace =\"Food\", value = \"Food Industry\", inplace = True)dataframe.replace(to_replace =\"IT\", value = \"IT Industry\", inplace = True) # writing the dataframe to another csv filedataframe.to_csv('outputfile.csv', index = False)", "e": 28178, "s": 27568, "text": null }, { "code": null, "e": 28186, "s": 28178, "text": "Output:" }, { "code": null, "e": 28197, "s": 28186, "text": "python-csv" }, { "code": null, "e": 28211, "s": 28197, "text": "Python-pandas" }, { "code": null, "e": 28218, "s": 28211, "text": "Python" }, { "code": null, "e": 28316, "s": 28218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28334, "s": 28316, "text": "Python Dictionary" }, { "code": null, "e": 28369, "s": 28334, "text": "Read a file line by line in Python" }, { "code": null, "e": 28401, "s": 28369, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28423, "s": 28401, "text": "Enumerate() in Python" }, { "code": null, "e": 28465, "s": 28423, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28495, "s": 28465, "text": "Iterate over a list in Python" }, { "code": null, "e": 28524, "s": 28495, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28568, "s": 28524, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28605, "s": 28568, "text": "Create a Pandas DataFrame from Lists" } ]
How to dismiss the dialog with click on outside of the dialog?
This example demonstrate about how to dismiss the dialog with click on outside of the dialog Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/click" android:layout_width = "wrap_content" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click"/> </LinearLayout> In the above code, we have taken text view. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView text; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.click); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); } private void showAlertDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("AlertDialog"); alertDialog.setMessage("Sairamkrishna Mammahe do you wanna close it or not?"); alertDialog.setIcon(R.drawable.logo); alertDialog.setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this,"you clicked on yes button",Toast.LENGTH_LONG).show(); } }); alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(false); alert.show(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on textview to open Alert Dialog. Click here to download the project code
[ { "code": null, "e": 1155, "s": 1062, "text": "This example demonstrate about how to dismiss the dialog with click on outside of the dialog" }, { "code": null, "e": 1284, "s": 1155, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1349, "s": 1284, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1794, "s": 1349, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:textSize = \"30sp\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"/>\n</LinearLayout>" }, { "code": null, "e": 1838, "s": 1794, "text": "In the above code, we have taken text view." }, { "code": null, "e": 1895, "s": 1838, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3614, "s": 1895, "text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.content.DialogInterface;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.click);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n showAlertDialog();\n }\n });\n }\n private void showAlertDialog() {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n alertDialog.setTitle(\"AlertDialog\");\n alertDialog.setMessage(\"Sairamkrishna Mammahe do you wanna close it or not?\");\n alertDialog.setIcon(R.drawable.logo);\n alertDialog.setPositiveButton(\"yes\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n Toast.makeText(MainActivity.this,\"you clicked on yes button\",Toast.LENGTH_LONG).show();\n }\n });\n alertDialog.setNegativeButton(\"No\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n }\n });\n AlertDialog alert = alertDialog.create();\n alert.setCanceledOnTouchOutside(false);\n alert.show();\n }\n}" }, { "code": null, "e": 3961, "s": 3614, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4005, "s": 3961, "text": "Now click on textview to open Alert Dialog." }, { "code": null, "e": 4045, "s": 4005, "text": "Click here to download the project code" } ]
Large input field with Bootstrap
Use the .input-lg class to set large input field in Bootstrap. You can try to run the following code to implement .input-lg class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Candidate Profile</h2> <form> <div class = "form-group"> <label for = "sel2">What is your job profile?</label> <select class = "form-control input-lg" id = "sel2"> <option>Programmer</option> <option>Web Developer</option> <option>DBA</option> <option>Support Engineer</option> </select> </div> <div class = "form-group"> <label for = "sel3">Educational Qualifcation</label> <select class = "form-control input-sm" id = "sel3"> <option>Undergraduate</option> <option>Graduate</option> <option>Post-Graduate</option> </select> </div> </form> </div> </body> </html>
[ { "code": null, "e": 1125, "s": 1062, "text": "Use the .input-lg class to set large input field in Bootstrap." }, { "code": null, "e": 1194, "s": 1125, "text": "You can try to run the following code to implement .input-lg class −" }, { "code": null, "e": 1204, "s": 1194, "text": "Live Demo" }, { "code": null, "e": 2629, "s": 1204, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Candidate Profile</h2>\n <form>\n <div class = \"form-group\">\n <label for = \"sel2\">What is your job profile?</label>\n <select class = \"form-control input-lg\" id = \"sel2\">\n <option>Programmer</option>\n <option>Web Developer</option>\n <option>DBA</option>\n <option>Support Engineer</option>\n </select>\n </div>\n <div class = \"form-group\">\n <label for = \"sel3\">Educational Qualifcation</label>\n <select class = \"form-control input-sm\" id = \"sel3\">\n <option>Undergraduate</option>\n <option>Graduate</option>\n <option>Post-Graduate</option>\n </select>\n </div>\n </form>\n </div>\n </body>\n</html>" } ]
Newspaper: Article scraping & curation (Python) - GeeksforGeeks
30 Nov, 2021 Newspaper is a Python module used for extracting and parsing newspaper articles. Newspaper use advance algorithms with web scraping to extract all the useful text from a website. It works amazingly well on online newspapers websites. Since it use web scraping too many request to a newspaper website may lead to blocking, so use it accordingly. Installation: pip install newspaper3k Newspaper supports following languages: input code full name ar Arabic da Danish de German el Greek en English it Italian zh Chinese ......... and many more Some Useful functionsTo create an instance of an article article_name = Article(url, language="language code according to newspaper") To download an article article_name.download() To parse an article article_name.parse() To apply nlp(natural language processing) on article article_name.nlp() To extract article’s text article_name.text To extract article’s title article_name.title To extract article’s summary article_name.summary To extract article’s keywords article_name.keywords Python from newspaper import Article #A new article from TOIurl = "http:// timesofindia.indiatimes.com/world/china/chinese-expert-warns-of-troops-entering-kashmir/articleshow/59516912.cms" #For different language newspaper refer above tabletoi_article = Article(url, language="en") # en for English #To download the articletoi_article.download() #To parse the articletoi_article.parse() #To perform natural language processing ie..nlptoi_article.nlp() #To extract titleprint("Article's Title:")print(toi_article.title)print("n") #To extract textprint("Article's Text:")print(toi_article.text)print("n") #To extract summaryprint("Article's Summary:")print(toi_article.summary)print("n") #To extract keywordsprint("Article's Keywords:")print(toi_article.keywords) Output: Article's Title: India China News: Chinese expert warns of troops entering Kashmir Article's Text: BEIJING: A Chinese expert has argued that his country's troops would be entitled to enter the Indian side of Kashmir by extending the logic that has permitted Indian troops to enter an area which is disputed by China and Bhutan This is one of the several arguments made by the scholar in an attempt to blame India for. India has responded to efforts by China to build a road in the Doklam area, which falls next to the trijunction connecting Sikkim with Tibet and Bhutan and"Even if India were requested to defend Bhutan's territory, this could only be limited to its established territory, not the disputed area, " Long Xingchun, director of the Center for Indian Studies at China West Normal University said in an article. "Otherwise, under India's logic, if the Pakistani government requests, a third country's army can enter the area disputed by India and Pakistan, including India-controlled Kashmir".China is not just interfering, it is building roads and other infrastructure projects right inside Pakistan-Occupied Kashmir (PoK), which is claimed by both India and Pakistan. This is one of the facts that the article did not mention.The scholar, through his article in the Beijing-based Global Times, suggested that Beijing can internationalize the Doklam controversy without worrying about western countries supporting India because the West has a lot of business to do with China."China can show the region and the international community or even the UN Security Council its evidence to illustrate China's position, " Long said. At the same time, he complained that "Western governments and media kept silent, ignoring India's hegemony over the small countries of South Asia" when India imposed a blockade on the flow of goods to Nepal in 2015.Recent actions by US president Donald Trump, which include selling arms to Taiwan and pressuring China on the North Korean issue, shows that the West is not necessarily cowered down by China's business capabilities.He reiterated the government's stated line that Doklam belongs to China, and that Indian troops had entered the area under the guise of helping Bhutan protect its territory."For a long time, India has been talking about international equality and non-interference in the internal affairs of others, but it has pursued hegemonic diplomacy in South Asia, seriously violating the UN Charter and undermining the basic norms of international relations, " he said.Interestingly, Chinese scholars are worrying about India interfering in Bhutan's "sovereignty and national interests" even though it is Chinese troops who have entered the Doklam area claimed by it."Indians have migrated in large numbers to Nepal and Bhutan, interfering with Nepal's internal affairs. The first challenge for Nepal and Bhutan is to avoid becoming a state of India, like Sikkim, " he said. Article's Summary: sending its troops to the disputed Doklam area +puts Indian territory at risk +BEIJING: A Chinese expert has argued that his country's troops would be entitled to enter the Indian side of Kashmir by extending the logic that has permitted Indian troops to enter an area which is disputed by China and Bhutan This is one of the several arguments made by the scholar in an attempt to blame India for. "Otherwise, under India's logic, if the Pakistani government requests, a third country's army can enter the area disputed by India and Pakistan, including India-controlled Kashmir".China is not just interfering, it is building roads and other infrastructure projects right inside Pakistan-Occupied Kashmir (PoK), which is claimed by both India and Pakistan. "China can show the region and the international community or even the UN Security Council its evidence to illustrate China's position, " Long said. "Indians have migrated in large numbers to Nepal and Bhutan, interfering with Nepal's internal affairs. The first challenge for Nepal and Bhutan is to avoid becoming a state of India, like Sikkim, " he said. Article's Keywords: ['troops', 'india', 'china', 'territory', 'west', 'disputed', 'expert', 'indian', 'bhutan', 'kashmir', 'chinese', 'entering', 'doklam', 'area', 'warns'] Reference: Newspaper python package on github This article is contributed by Pratik Chhajer. 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. Akanksha_Rai sagar0719kumar adnanirshad158 surinderdawra388 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24360, "s": 24332, "text": "\n30 Nov, 2021" }, { "code": null, "e": 24705, "s": 24360, "text": "Newspaper is a Python module used for extracting and parsing newspaper articles. Newspaper use advance algorithms with web scraping to extract all the useful text from a website. It works amazingly well on online newspapers websites. Since it use web scraping too many request to a newspaper website may lead to blocking, so use it accordingly." }, { "code": null, "e": 24720, "s": 24705, "text": "Installation: " }, { "code": null, "e": 24744, "s": 24720, "text": "pip install newspaper3k" }, { "code": null, "e": 24786, "s": 24744, "text": "Newspaper supports following languages: " }, { "code": null, "e": 25025, "s": 24786, "text": " input code full name\n ar Arabic\n da Danish\n de German\n el Greek\n en English\n it Italian\n zh Chinese\n......... and many more" }, { "code": null, "e": 25083, "s": 25025, "text": "Some Useful functionsTo create an instance of an article " }, { "code": null, "e": 25160, "s": 25083, "text": "article_name = Article(url, language=\"language code according to newspaper\")" }, { "code": null, "e": 25184, "s": 25160, "text": "To download an article " }, { "code": null, "e": 25208, "s": 25184, "text": "article_name.download()" }, { "code": null, "e": 25229, "s": 25208, "text": "To parse an article " }, { "code": null, "e": 25250, "s": 25229, "text": "article_name.parse()" }, { "code": null, "e": 25304, "s": 25250, "text": "To apply nlp(natural language processing) on article " }, { "code": null, "e": 25323, "s": 25304, "text": "article_name.nlp()" }, { "code": null, "e": 25350, "s": 25323, "text": "To extract article’s text " }, { "code": null, "e": 25368, "s": 25350, "text": "article_name.text" }, { "code": null, "e": 25396, "s": 25368, "text": "To extract article’s title " }, { "code": null, "e": 25415, "s": 25396, "text": "article_name.title" }, { "code": null, "e": 25445, "s": 25415, "text": "To extract article’s summary " }, { "code": null, "e": 25466, "s": 25445, "text": "article_name.summary" }, { "code": null, "e": 25497, "s": 25466, "text": "To extract article’s keywords " }, { "code": null, "e": 25519, "s": 25497, "text": "article_name.keywords" }, { "code": null, "e": 25526, "s": 25519, "text": "Python" }, { "code": "from newspaper import Article #A new article from TOIurl = \"http:// timesofindia.indiatimes.com/world/china/chinese-expert-warns-of-troops-entering-kashmir/articleshow/59516912.cms\" #For different language newspaper refer above tabletoi_article = Article(url, language=\"en\") # en for English #To download the articletoi_article.download() #To parse the articletoi_article.parse() #To perform natural language processing ie..nlptoi_article.nlp() #To extract titleprint(\"Article's Title:\")print(toi_article.title)print(\"n\") #To extract textprint(\"Article's Text:\")print(toi_article.text)print(\"n\") #To extract summaryprint(\"Article's Summary:\")print(toi_article.summary)print(\"n\") #To extract keywordsprint(\"Article's Keywords:\")print(toi_article.keywords)", "e": 26281, "s": 25526, "text": null }, { "code": null, "e": 26290, "s": 26281, "text": "Output: " }, { "code": null, "e": 30533, "s": 26290, "text": "Article's Title:\nIndia China News: Chinese expert warns of troops entering Kashmir\n\n\nArticle's Text:\nBEIJING: A Chinese expert has argued that his country's troops would be entitled to enter the Indian side of Kashmir by extending the logic that has permitted Indian troops to enter an area which is disputed by China and Bhutan This is one of the several arguments made by the scholar in an attempt to blame India for. India has responded to efforts by China to build a road in the Doklam area, which falls next to the trijunction connecting Sikkim with Tibet and Bhutan and\"Even if India were requested to defend Bhutan's territory, this could only be limited to its established territory, not the disputed area, \" Long Xingchun, director of the Center for Indian Studies at China West Normal University said in an article. \"Otherwise, under India's logic, if the Pakistani government requests, a third country's army can enter the area disputed by India and Pakistan, including India-controlled Kashmir\".China is not just interfering, it is building roads and other infrastructure projects right inside Pakistan-Occupied Kashmir (PoK), which is claimed by both India and Pakistan. This is one of the facts that the article did not mention.The scholar, through his article in the Beijing-based Global Times, suggested that Beijing can internationalize the Doklam controversy without worrying about western countries supporting India because the West has a lot of business to do with China.\"China can show the region and the international community or even the UN Security Council its evidence to illustrate China's position, \" Long said. At the same time, he complained that \"Western governments and media kept silent, ignoring India's hegemony over the small countries of South Asia\" when India imposed a blockade on the flow of goods to Nepal in 2015.Recent actions by US president Donald Trump, which include selling arms to Taiwan and pressuring China on the North Korean issue, shows that the West is not necessarily cowered down by China's business capabilities.He reiterated the government's stated line that Doklam belongs to China, and that Indian troops had entered the area under the guise of helping Bhutan protect its territory.\"For a long time, India has been talking about international equality and non-interference in the internal affairs of others, but it has pursued hegemonic diplomacy in South Asia, seriously violating the UN Charter and undermining the basic norms of international relations, \" he said.Interestingly, Chinese scholars are worrying about India interfering in Bhutan's \"sovereignty and national interests\" even though it is Chinese troops who have entered the Doklam area claimed by it.\"Indians have migrated in large numbers to Nepal and Bhutan, interfering with Nepal's internal affairs. The first challenge for Nepal and Bhutan is to avoid becoming a state of India, like Sikkim, \" he said.\n\n\nArticle's Summary:\nsending its troops to the disputed Doklam area +puts Indian territory at risk +BEIJING: A Chinese expert has argued that his country's troops would be entitled to enter the Indian side of Kashmir by extending the logic that has permitted Indian troops to enter an area which is disputed by China and Bhutan This is one of the several arguments made by the scholar in an attempt to blame India for.\n\"Otherwise, under India's logic, if the Pakistani government requests, a third country's army can enter the area disputed by India and Pakistan, including India-controlled Kashmir\".China is not just interfering, it is building roads and other infrastructure projects right inside Pakistan-Occupied Kashmir (PoK), which is claimed by both India and Pakistan.\n\"China can show the region and the international community or even the UN Security Council its evidence to illustrate China's position, \" Long said.\n\"Indians have migrated in large numbers to Nepal and Bhutan, interfering with Nepal's internal affairs.\nThe first challenge for Nepal and Bhutan is to avoid becoming a state of India, like Sikkim, \" he said.\n\n\nArticle's Keywords:\n['troops', 'india', 'china', 'territory', 'west', 'disputed', 'expert', 'indian', 'bhutan', 'kashmir', 'chinese', 'entering', 'doklam', 'area', 'warns']" }, { "code": null, "e": 30579, "s": 30533, "text": "Reference: Newspaper python package on github" }, { "code": null, "e": 31002, "s": 30579, "text": "This article is contributed by Pratik Chhajer. 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": 31015, "s": 31002, "text": "Akanksha_Rai" }, { "code": null, "e": 31030, "s": 31015, "text": "sagar0719kumar" }, { "code": null, "e": 31045, "s": 31030, "text": "adnanirshad158" }, { "code": null, "e": 31062, "s": 31045, "text": "surinderdawra388" }, { "code": null, "e": 31077, "s": 31062, "text": "python-utility" }, { "code": null, "e": 31084, "s": 31077, "text": "Python" }, { "code": null, "e": 31182, "s": 31084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31200, "s": 31182, "text": "Python Dictionary" }, { "code": null, "e": 31235, "s": 31200, "text": "Read a file line by line in Python" }, { "code": null, "e": 31257, "s": 31235, "text": "Enumerate() in Python" }, { "code": null, "e": 31289, "s": 31257, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31319, "s": 31289, "text": "Iterate over a list in Python" }, { "code": null, "e": 31361, "s": 31319, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31387, "s": 31361, "text": "Python String | replace()" }, { "code": null, "e": 31424, "s": 31387, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 31467, "s": 31424, "text": "Python program to convert a list to string" } ]
Set Date value in Java HashMap?
Create a Calendar instance and Date object − Calendar cal = Calendar.getInstance(); Date date = new Date(); cal.setTime(date); Now, create a HashMap and store Date value − LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>(); hashMap.put("year", cal.get(Calendar.YEAR)); hashMap.put("month", cal.get(Calendar.MONTH)); hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH)); Live Demo import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; public class Demo { public static void main(String[] argv) { Calendar cal = Calendar.getInstance(); Date date = new Date(); System.out.println("Date = "+date); cal.setTime(date); LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>(); hashMap.put("year", cal.get(Calendar.YEAR)); hashMap.put("month", cal.get(Calendar.MONTH)); hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH)); System.out.println("HashMap (Date) = "+hashMap); hashMap.put("hour", cal.get(Calendar.HOUR_OF_DAY)); hashMap.put("minute", cal.get(Calendar.MINUTE)); hashMap.put("second", cal.get(Calendar.SECOND)); hashMap.put("millisecond", cal.get(Calendar.MILLISECOND)); System.out.println("HashMap (DateTime) = "+hashMap); } } Date = Fri Apr 19 17:45:24 IST 2019 HashMap (Date) = {year=2019, month=3, day=19} HashMap (DateTime) = {year=2019, month=3, day=19, hour=17, minute=45, second=24, millisecond=98}
[ { "code": null, "e": 1107, "s": 1062, "text": "Create a Calendar instance and Date object −" }, { "code": null, "e": 1189, "s": 1107, "text": "Calendar cal = Calendar.getInstance();\nDate date = new Date();\ncal.setTime(date);" }, { "code": null, "e": 1234, "s": 1189, "text": "Now, create a HashMap and store Date value −" }, { "code": null, "e": 1456, "s": 1234, "text": "LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();\nhashMap.put(\"year\", cal.get(Calendar.YEAR));\nhashMap.put(\"month\", cal.get(Calendar.MONTH));\nhashMap.put(\"day\", cal.get(Calendar.DAY_OF_MONTH));" }, { "code": null, "e": 1467, "s": 1456, "text": " Live Demo" }, { "code": null, "e": 2355, "s": 1467, "text": "import java.util.Calendar;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\npublic class Demo {\n public static void main(String[] argv) {\n Calendar cal = Calendar.getInstance();\n Date date = new Date();\n System.out.println(\"Date = \"+date);\n cal.setTime(date);\n LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();\n hashMap.put(\"year\", cal.get(Calendar.YEAR));\n hashMap.put(\"month\", cal.get(Calendar.MONTH));\n hashMap.put(\"day\", cal.get(Calendar.DAY_OF_MONTH));\n System.out.println(\"HashMap (Date) = \"+hashMap);\n hashMap.put(\"hour\", cal.get(Calendar.HOUR_OF_DAY));\n hashMap.put(\"minute\", cal.get(Calendar.MINUTE));\n hashMap.put(\"second\", cal.get(Calendar.SECOND));\n hashMap.put(\"millisecond\", cal.get(Calendar.MILLISECOND));\n System.out.println(\"HashMap (DateTime) = \"+hashMap);\n }\n}" }, { "code": null, "e": 2534, "s": 2355, "text": "Date = Fri Apr 19 17:45:24 IST 2019\nHashMap (Date) = {year=2019, month=3, day=19}\nHashMap (DateTime) = {year=2019, month=3, day=19, hour=17, minute=45, second=24, millisecond=98}" } ]
Essential Math for Data Science: Introduction to Linear Algebra | by Hadrien Jean | Towards Data Science
Machines only understand numbers. For instance, if you want to create a spam detector, you have first to convert your text data into numbers (for instance, through word embeddings). Data can then be stored in vectors, matrices, and tensors. For instance, images are represented as matrices of values between 0 and 255 representing the luminosity of each color for each pixel. It is possible to leverage the tools and concepts from the field of linear algebra to manipulate these vectors, matrices, and tensors. Linear algebra is the branch of mathematics that studies vector spaces. You’ll see how vectors constitute vector spaces and how linear algebra applies linear transformations to these spaces. You’ll also learn the powerful relationship between sets of linear equations and vector equations, related to important data science concepts like least squares approximation. You’ll finally learn important matrix decomposition methods: eigendecomposition and Singular Value Decomposition (SVD), important to understand unsupervised learning methods like Principal Component Analysis (PCA). Linear algebra deals with vectors. Other mathematical entities in the field can be defined by their relationship to vectors: scalars, for example, are single numbers that scale vectors (stretching or contracting) when they are multiplied by them. However, vectors refer to various concepts according to the field they are used in. In the context of data science, they are a way to store values from your data. For instance, take the height and weight of people: since they are distinct values with different meanings, you need to store them separately, for instance using two vectors. You can then do operations on vectors to manipulate these features without losing the fact that the values correspond to different attributes. You can also use vectors to store data samples, for instance, store the height of ten people as a vector containing ten values. We’ll use lowercase, boldface letters to name vectors (such as v). As usual, refer to the Appendix Essential Math for Data Science to have the summary of the notations used in this book. The word vector can refer to multiple concepts. Let’s learn more about geometric and coordinate vectors. Coordinates are values describing a position. For instance, any position on earth can be specified by geographical coordinates (latitude, longitude, and elevation). Geometric vectors, also called Euclidean vectors, are mathematical objects defined by their magnitude (the length) and their direction. These properties allow you to describe the displacement from a location to another. For instance, Figure 1 shows that the point A has coordinates (1, 1) and the point B has coordinates (3, 2). The geometric vector v describes the displacement from A to B, but since vectors are defined by their magnitude and direction, you can also represent v as starting from the origin. Cartesian Plane In Figure 1, we used a coordinate system called the Cartesian plane. The horizontal and vertical lines are the coordinate axes, usually labeled respectively x and y. The intersection of the two coordinates is called the origin and corresponds to the coordinate 0 for each axis. In a Cartesian plane, any position can be specified by the x and the y coordinates. The Cartesian coordinate system can be extended to more dimensions: the position of a point in a n-dimensional space is specified by n coordinates. The real coordinate n-dimensional space, containing n-tuples of real numbers, is named Rn . For instance, the space R2 is the two-dimensional space containing pairs of real numbers (the coordinates). In three dimensions (R3), a point in space is represented by three real numbers. Coordinate vectors are ordered lists of numbers corresponding to the vector coordinates. Since vector initial points are at the origin, you need to encode only the coordinates of the terminal point. For instance, let’s take the vector v represented in Figure 2. The corresponding coordinate vector is as follows: Each value is associated with a direction: in this case, the first value corresponds to the x-axis direction and the second number to the y-axis. As illustrated in Figure 3, these values are called components or entries of the vector. In addition, as represented in Figure 4, you can simply represent the terminal point of the arrow: this is a scatter-plot. Indexing refers to the process of getting a vector component (one of the values from the vector) using its position (its index). Python uses zero-based indexing, meaning that the first index is zero. However mathematically, the convention is to use one-based indexing. I’ll denote the component i of the vector v with a subscript, as v_i, without bold font because the component of the vector is a scalar. In Numpy, vectors are called one-dimensional arrays. You can use the function np.array() to create one: array([3, 2]) Let’s take the example of v, a three-dimensional vector defined as follows: As shown in Figure 5, you can reach the endpoint of the vector by traveling 3 units on the x-axis, 4 on the y-axis, and 2 on the z-axis. More generally, in a n-dimensional space, the position of a terminal point is described by n components. You can denote the dimensionality of a vector using the set notation Rn. It expresses the real coordinate space: this is the n-dimensional space with real numbers as coordinate values. For instance, vectors in R3 have three components, as the following vector v for example: In the context of data science, you can use coordinate vectors to represent your data. You can represent data samples as vectors with each component corresponding to a feature. For instance, in a real estate dataset, you could have a vector corresponding to an apartment with its features as different components (like the number of rooms, the location, etc.). Another way to do it is to create one vector per feature, each containing all observations. Storing data in vectors allows you to leverage linear algebra tools. Note that, even if you can’t visualize vectors with a large number of components, you can still apply the same operations on them. This means that you can get insights about linear algebra using two or three dimensions, and then, use what you learn with a larger number of dimensions. The dot product (referring to the dot symbol used to characterize this operation), also called scalar product, is an operation done on vectors. It takes two vectors, but unlike addition and scalar multiplication, it returns a single number (a scalar, hence the name). It is an example of a more general operation called the inner product. Figure 6 shows an illustration of how the dot product works. You can see that it corresponds to the sum of the multiplication of the components with the same index. The dot product between two vectors u and v, denoted by the symbol ⋅, is defined as the sum of the product of each pair of components. More formally, it is expressed as: with m the number of components of the vectors u and v (they must have the same number of components), and ii the index of the current vector component. Dot Symbol. Note that the symbol of the dot product is the same as the dot used to refer to multiplication between scalars. The context (if the elements are scalars or vectors) tells you which one it is. Let’s take an example. You have the following vectors: and The dot product of these two vectors is defined as: The dot product between u and v is 35. It converts the two vectors u and v into a scalar. Let’s use Numpy to calculate the dot product of these vectors. You can use the method dot() of Numpy arrays: 35 It is also possible to use the following equivalent syntax: 35 Or, with Python 3.5+, it is also possible to use the @ operator: 35 Vector Multiplication Note that the dot product is different from the element-wise multiplication, also called the Hadamard product, which returns another vector. The symbol ⊙ is generally used to characterize this operation. For instance: The squared L2 norm can be calculated using the dot product of the vector with itself (u ⋅ u): This is an important property in machine learning, as you saw in Essential Math for Data Science. The dot product between two orthogonal vectors is equal to 0. In addition, the dot product between a unit vector and itself is equal to 1. How can you interpret the dot product operation with geometric vectors? You have seen in Essential Math for Data Science the geometric interpretation of the addition and scalar multiplication of vectors, but what about the dot product? Let’s take the two following vectors: and What is the meaning of this scalar? Well, it is related to the idea of projecting u onto v. As shown in Figure 7, the projection of u on the line with the direction of v is like the shadow of the vector u on this line. The value of the dot product (6 in our example) corresponds to the multiplication of the length of v and the length of the projection of u on v. Note that the elements are scalars, so the dot symbol refers to a multiplication of these values. And you have: The projection of u onto v is defined as follows (you can refer to Essential Math for Data Science to see the mathematical details about the projection of a vector onto a line): Finally, the multiplication of the length of v and the length of the projection is: This shows that you can think of the dot product on geometric vectors as a projection. Using the projection gives you the same result as with the dot product formula. Furthermore, the value that you obtain with the dot product tells you the relationship between the two vectors. If this value is positive, the angle between the vectors is less than 90 degrees, if it is negative, the angle is greater than 90 degrees, if it is zero, the vectors are orthogonal and the angle is 90 degrees. Let’s review some properties of the dot product. The dot product is distributive. This means that, for instance, with the three vectors u, v, and w, you have: The dot product is not associative, meaning that the order of the operations matters. For instance: The dot product is not a binary operator: the result of the dot product between two vectors is not another vector (but a scalar). The dot product between vectors is said to be commutative. This means that the order of the vectors around the dot product doesn’t matter. You have: However, be careful, because this is not necessarily true for matrices. This post shows the basics of linear algebra. Scalars and vectors are building blocks of more complex structures as you’ll see in my next linear algebra posts. For instance, we’ll see that the dot product can be extended to matrices with the matrix product! Originally published at https://hadrienj.github.io/posts/Essential-Math-for-Data-Science-Scalars-Vectors-and-the-Dot-Product/. This post is a sample of my book Essential Math for Data Science! Get the book here: https://bit.ly/3gBViVX!
[ { "code": null, "e": 683, "s": 172, "text": "Machines only understand numbers. For instance, if you want to create a spam detector, you have first to convert your text data into numbers (for instance, through word embeddings). Data can then be stored in vectors, matrices, and tensors. For instance, images are represented as matrices of values between 0 and 255 representing the luminosity of each color for each pixel. It is possible to leverage the tools and concepts from the field of linear algebra to manipulate these vectors, matrices, and tensors." }, { "code": null, "e": 1265, "s": 683, "text": "Linear algebra is the branch of mathematics that studies vector spaces. You’ll see how vectors constitute vector spaces and how linear algebra applies linear transformations to these spaces. You’ll also learn the powerful relationship between sets of linear equations and vector equations, related to important data science concepts like least squares approximation. You’ll finally learn important matrix decomposition methods: eigendecomposition and Singular Value Decomposition (SVD), important to understand unsupervised learning methods like Principal Component Analysis (PCA)." }, { "code": null, "e": 1512, "s": 1265, "text": "Linear algebra deals with vectors. Other mathematical entities in the field can be defined by their relationship to vectors: scalars, for example, are single numbers that scale vectors (stretching or contracting) when they are multiplied by them." }, { "code": null, "e": 1993, "s": 1512, "text": "However, vectors refer to various concepts according to the field they are used in. In the context of data science, they are a way to store values from your data. For instance, take the height and weight of people: since they are distinct values with different meanings, you need to store them separately, for instance using two vectors. You can then do operations on vectors to manipulate these features without losing the fact that the values correspond to different attributes." }, { "code": null, "e": 2121, "s": 1993, "text": "You can also use vectors to store data samples, for instance, store the height of ten people as a vector containing ten values." }, { "code": null, "e": 2308, "s": 2121, "text": "We’ll use lowercase, boldface letters to name vectors (such as v). As usual, refer to the Appendix Essential Math for Data Science to have the summary of the notations used in this book." }, { "code": null, "e": 2413, "s": 2308, "text": "The word vector can refer to multiple concepts. Let’s learn more about geometric and coordinate vectors." }, { "code": null, "e": 2578, "s": 2413, "text": "Coordinates are values describing a position. For instance, any position on earth can be specified by geographical coordinates (latitude, longitude, and elevation)." }, { "code": null, "e": 2798, "s": 2578, "text": "Geometric vectors, also called Euclidean vectors, are mathematical objects defined by their magnitude (the length) and their direction. These properties allow you to describe the displacement from a location to another." }, { "code": null, "e": 3088, "s": 2798, "text": "For instance, Figure 1 shows that the point A has coordinates (1, 1) and the point B has coordinates (3, 2). The geometric vector v describes the displacement from A to B, but since vectors are defined by their magnitude and direction, you can also represent v as starting from the origin." }, { "code": null, "e": 3104, "s": 3088, "text": "Cartesian Plane" }, { "code": null, "e": 3382, "s": 3104, "text": "In Figure 1, we used a coordinate system called the Cartesian plane. The horizontal and vertical lines are the coordinate axes, usually labeled respectively x and y. The intersection of the two coordinates is called the origin and corresponds to the coordinate 0 for each axis." }, { "code": null, "e": 3895, "s": 3382, "text": "In a Cartesian plane, any position can be specified by the x and the y coordinates. The Cartesian coordinate system can be extended to more dimensions: the position of a point in a n-dimensional space is specified by n coordinates. The real coordinate n-dimensional space, containing n-tuples of real numbers, is named Rn . For instance, the space R2 is the two-dimensional space containing pairs of real numbers (the coordinates). In three dimensions (R3), a point in space is represented by three real numbers." }, { "code": null, "e": 4094, "s": 3895, "text": "Coordinate vectors are ordered lists of numbers corresponding to the vector coordinates. Since vector initial points are at the origin, you need to encode only the coordinates of the terminal point." }, { "code": null, "e": 4208, "s": 4094, "text": "For instance, let’s take the vector v represented in Figure 2. The corresponding coordinate vector is as follows:" }, { "code": null, "e": 4354, "s": 4208, "text": "Each value is associated with a direction: in this case, the first value corresponds to the x-axis direction and the second number to the y-axis." }, { "code": null, "e": 4443, "s": 4354, "text": "As illustrated in Figure 3, these values are called components or entries of the vector." }, { "code": null, "e": 4566, "s": 4443, "text": "In addition, as represented in Figure 4, you can simply represent the terminal point of the arrow: this is a scatter-plot." }, { "code": null, "e": 4695, "s": 4566, "text": "Indexing refers to the process of getting a vector component (one of the values from the vector) using its position (its index)." }, { "code": null, "e": 4972, "s": 4695, "text": "Python uses zero-based indexing, meaning that the first index is zero. However mathematically, the convention is to use one-based indexing. I’ll denote the component i of the vector v with a subscript, as v_i, without bold font because the component of the vector is a scalar." }, { "code": null, "e": 5076, "s": 4972, "text": "In Numpy, vectors are called one-dimensional arrays. You can use the function np.array() to create one:" }, { "code": null, "e": 5090, "s": 5076, "text": "array([3, 2])" }, { "code": null, "e": 5166, "s": 5090, "text": "Let’s take the example of v, a three-dimensional vector defined as follows:" }, { "code": null, "e": 5303, "s": 5166, "text": "As shown in Figure 5, you can reach the endpoint of the vector by traveling 3 units on the x-axis, 4 on the y-axis, and 2 on the z-axis." }, { "code": null, "e": 5408, "s": 5303, "text": "More generally, in a n-dimensional space, the position of a terminal point is described by n components." }, { "code": null, "e": 5593, "s": 5408, "text": "You can denote the dimensionality of a vector using the set notation Rn. It expresses the real coordinate space: this is the n-dimensional space with real numbers as coordinate values." }, { "code": null, "e": 5683, "s": 5593, "text": "For instance, vectors in R3 have three components, as the following vector v for example:" }, { "code": null, "e": 5770, "s": 5683, "text": "In the context of data science, you can use coordinate vectors to represent your data." }, { "code": null, "e": 6044, "s": 5770, "text": "You can represent data samples as vectors with each component corresponding to a feature. For instance, in a real estate dataset, you could have a vector corresponding to an apartment with its features as different components (like the number of rooms, the location, etc.)." }, { "code": null, "e": 6136, "s": 6044, "text": "Another way to do it is to create one vector per feature, each containing all observations." }, { "code": null, "e": 6490, "s": 6136, "text": "Storing data in vectors allows you to leverage linear algebra tools. Note that, even if you can’t visualize vectors with a large number of components, you can still apply the same operations on them. This means that you can get insights about linear algebra using two or three dimensions, and then, use what you learn with a larger number of dimensions." }, { "code": null, "e": 6829, "s": 6490, "text": "The dot product (referring to the dot symbol used to characterize this operation), also called scalar product, is an operation done on vectors. It takes two vectors, but unlike addition and scalar multiplication, it returns a single number (a scalar, hence the name). It is an example of a more general operation called the inner product." }, { "code": null, "e": 6994, "s": 6829, "text": "Figure 6 shows an illustration of how the dot product works. You can see that it corresponds to the sum of the multiplication of the components with the same index." }, { "code": null, "e": 7164, "s": 6994, "text": "The dot product between two vectors u and v, denoted by the symbol ⋅, is defined as the sum of the product of each pair of components. More formally, it is expressed as:" }, { "code": null, "e": 7317, "s": 7164, "text": "with m the number of components of the vectors u and v (they must have the same number of components), and ii the index of the current vector component." }, { "code": null, "e": 7521, "s": 7317, "text": "Dot Symbol. Note that the symbol of the dot product is the same as the dot used to refer to multiplication between scalars. The context (if the elements are scalars or vectors) tells you which one it is." }, { "code": null, "e": 7576, "s": 7521, "text": "Let’s take an example. You have the following vectors:" }, { "code": null, "e": 7580, "s": 7576, "text": "and" }, { "code": null, "e": 7632, "s": 7580, "text": "The dot product of these two vectors is defined as:" }, { "code": null, "e": 7722, "s": 7632, "text": "The dot product between u and v is 35. It converts the two vectors u and v into a scalar." }, { "code": null, "e": 7831, "s": 7722, "text": "Let’s use Numpy to calculate the dot product of these vectors. You can use the method dot() of Numpy arrays:" }, { "code": null, "e": 7834, "s": 7831, "text": "35" }, { "code": null, "e": 7894, "s": 7834, "text": "It is also possible to use the following equivalent syntax:" }, { "code": null, "e": 7897, "s": 7894, "text": "35" }, { "code": null, "e": 7962, "s": 7897, "text": "Or, with Python 3.5+, it is also possible to use the @ operator:" }, { "code": null, "e": 7965, "s": 7962, "text": "35" }, { "code": null, "e": 7987, "s": 7965, "text": "Vector Multiplication" }, { "code": null, "e": 8205, "s": 7987, "text": "Note that the dot product is different from the element-wise multiplication, also called the Hadamard product, which returns another vector. The symbol ⊙ is generally used to characterize this operation. For instance:" }, { "code": null, "e": 8300, "s": 8205, "text": "The squared L2 norm can be calculated using the dot product of the vector with itself (u ⋅ u):" }, { "code": null, "e": 8398, "s": 8300, "text": "This is an important property in machine learning, as you saw in Essential Math for Data Science." }, { "code": null, "e": 8537, "s": 8398, "text": "The dot product between two orthogonal vectors is equal to 0. In addition, the dot product between a unit vector and itself is equal to 1." }, { "code": null, "e": 8773, "s": 8537, "text": "How can you interpret the dot product operation with geometric vectors? You have seen in Essential Math for Data Science the geometric interpretation of the addition and scalar multiplication of vectors, but what about the dot product?" }, { "code": null, "e": 8811, "s": 8773, "text": "Let’s take the two following vectors:" }, { "code": null, "e": 8815, "s": 8811, "text": "and" }, { "code": null, "e": 8907, "s": 8815, "text": "What is the meaning of this scalar? Well, it is related to the idea of projecting u onto v." }, { "code": null, "e": 9179, "s": 8907, "text": "As shown in Figure 7, the projection of u on the line with the direction of v is like the shadow of the vector u on this line. The value of the dot product (6 in our example) corresponds to the multiplication of the length of v and the length of the projection of u on v." }, { "code": null, "e": 9291, "s": 9179, "text": "Note that the elements are scalars, so the dot symbol refers to a multiplication of these values. And you have:" }, { "code": null, "e": 9469, "s": 9291, "text": "The projection of u onto v is defined as follows (you can refer to Essential Math for Data Science to see the mathematical details about the projection of a vector onto a line):" }, { "code": null, "e": 9553, "s": 9469, "text": "Finally, the multiplication of the length of v and the length of the projection is:" }, { "code": null, "e": 9720, "s": 9553, "text": "This shows that you can think of the dot product on geometric vectors as a projection. Using the projection gives you the same result as with the dot product formula." }, { "code": null, "e": 10042, "s": 9720, "text": "Furthermore, the value that you obtain with the dot product tells you the relationship between the two vectors. If this value is positive, the angle between the vectors is less than 90 degrees, if it is negative, the angle is greater than 90 degrees, if it is zero, the vectors are orthogonal and the angle is 90 degrees." }, { "code": null, "e": 10091, "s": 10042, "text": "Let’s review some properties of the dot product." }, { "code": null, "e": 10201, "s": 10091, "text": "The dot product is distributive. This means that, for instance, with the three vectors u, v, and w, you have:" }, { "code": null, "e": 10301, "s": 10201, "text": "The dot product is not associative, meaning that the order of the operations matters. For instance:" }, { "code": null, "e": 10431, "s": 10301, "text": "The dot product is not a binary operator: the result of the dot product between two vectors is not another vector (but a scalar)." }, { "code": null, "e": 10580, "s": 10431, "text": "The dot product between vectors is said to be commutative. This means that the order of the vectors around the dot product doesn’t matter. You have:" }, { "code": null, "e": 10652, "s": 10580, "text": "However, be careful, because this is not necessarily true for matrices." }, { "code": null, "e": 10910, "s": 10652, "text": "This post shows the basics of linear algebra. Scalars and vectors are building blocks of more complex structures as you’ll see in my next linear algebra posts. For instance, we’ll see that the dot product can be extended to matrices with the matrix product!" }, { "code": null, "e": 11037, "s": 10910, "text": "Originally published at https://hadrienj.github.io/posts/Essential-Math-for-Data-Science-Scalars-Vectors-and-the-Dot-Product/." }, { "code": null, "e": 11103, "s": 11037, "text": "This post is a sample of my book Essential Math for Data Science!" } ]
Angular 2 Interview Questions
Dear readers, these Angular 2 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Angular 2. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework. Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft. TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft. Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications. Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications. Angular 2 has the following components − Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Component − This can be used to bring the modules together. Component − This can be used to bring the modules together. Templates − This is used to define the views of an Angular JS application. Templates − This is used to define the views of an Angular JS application. Metadata − This can be used to add more data to an Angular JS class. Metadata − This can be used to add more data to an Angular JS class. Service − This is used to create components which can be shared across the entire application. Service − This is used to create components which can be shared across the entire application. Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. A module is made up of the following parts − Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components.Following is the anatomy of a Component. A component consists of − Class − This is like a C or Java class which consists of properties and methods. Class − This is like a C or Java class which consists of properties and methods. Metadata − This is used to decorate the class and extend the functionality of the class. Metadata − This is used to decorate the class and extend the functionality of the class. Template − This is used to define the HTML view which is displayed in the application. Template − This is used to define the HTML view which is displayed in the application. A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module. ngIf − The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code. Syntax *ngIf = 'expression' If the expression evaluates to true then the corresponding gets added, else the elements are not added. ngIf − The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code. *ngIf = 'expression' If the expression evaluates to true then the corresponding gets added, else the elements are not added. ngFor − The ngFor element is used to elements based on the condition of the For loop. Syntax *ngFor = 'let variable of variablelist' The variable is a temporary variable to display the values in the variablelist. ngFor − The ngFor element is used to elements based on the condition of the For loop. *ngFor = 'let variable of variablelist' The variable is a temporary variable to display the values in the variablelist. Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function. The catch function contains a link to the Error Handler function. The catch function contains a link to the Error Handler function. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. Now, whenever you get an error it will be redirected to the error console of the browser. Now, whenever you get an error it will be redirected to the error console of the browser. Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user. Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application. Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection. Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module. @Injectable() export class classname { } Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator. @Component ({ providers : [classname] }) This file is used to give the options about TypeScript used for the Angular JS project. { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } Following are some key points to note about the above code. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true. The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile. The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile. This file contains information about Angular 2 project. Following are the typical settings in the file. { "name": "angular-quickstart", "version": "1.0.0", "description": "QuickStart package.json from the documentation, supplemented with testing support", "scripts": { "build": "tsc -p src/", "build:watch": "tsc -p src/ -w", "build:e2e": "tsc -p e2e/", "serve": "lite-server -c=bs-config.json", "serve:e2e": "lite-server -c=bs-config.e2e.json", "prestart": "npm run build", "start": "concurrently \"npm run build:watch\" \"npm run serve\"", "pree2e": "npm run build:e2e", "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --killothers --success first", "preprotractor": "webdriver-manager update", "protractor": "protractor protractor.config.js", "pretest": "npm run build", "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"", "pretest:once": "npm run build", "test:once": "karma start karma.conf.js --single-run", "lint": "tslint ./src/**/*.ts -t verbose" }, "keywords": [], "author": "", "license": "MIT", "dependencies": { "@angular/common": "<2.4.0", "@angular/compiler": "<2.4.0", "@angular/core": "<2.4.0", "@angular/forms": "<2.4.0", "@angular/http": "<2.4.0", "@angular/platform-browser": "<2.4.0", "@angular/platform-browser-dynamic": "<2.4.0", "@angular/router": "<3.4.0", "angular-in-memory-web-api": <0.2.4", "systemjs": "0.19.40", "core-js": "^2.4.1", "rxjs": "5.0.1", "zone.js": "^0.7.4" }, "devDependencies": { "concurrently": "^3.2.0", "lite-server": "^2.2.2", "typescript": "<2.0.10", "canonical-path": "0.0.2", "tslint": "^3.15.1", "lodash": "^4.16.4", "jasmine-core": "<2.4.1", "karma": "^1.3.0", "karma-chrome-launcher": "^2.0.0", "karma-cli": "^1.0.1", "karma-jasmine": "^1.0.2", "karma-jasmine-html-reporter": "^0.2.2", "protractor": <4.0.14", "rimraf": "^2.5.4", "@types/node": "^6.0.46", "@types/jasmine": "2.5.36" }, "repository": {} } Some key points to note about the above code − There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application. There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application. The "build:watch": "tsc -p src/ -w" command is used to compile the typescript in the background by looking for changes in the typescript files. The "build:watch": "tsc -p src/ -w" command is used to compile the typescript in the background by looking for changes in the typescript files. This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code. /** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // our app is within the app folder app: 'app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js' }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' } } }); })(this); Some key points to note about the above code − 'npm:': 'node_modules/' tells the location in our project where all the npm modules are located. 'npm:': 'node_modules/' tells the location in our project where all the npm modules are located. The mapping of app: 'app' tells the folder where all our applications files are loaded. The mapping of app: 'app' tells the folder where all our applications files are loaded. The following code will be present in the app.module.ts file. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Let's go through each line of the code in detail. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The BrowserModule is required by default for any web based angular application. The BrowserModule is required by default for any web based angular application. The bootstrap option tells Angular which Component to bootstrap in the application. The bootstrap option tells Angular which Component to bootstrap in the application. lowercase filter is used to convert the input to all lowercase. In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters. <div> The name of this Tutorial is {{TutorialName}} The first Topic is {{appList[0] | lowercase}} The second Topic is {{appList[1] | lowercase}} The third Topic is {{appList[2]| lowercase}} </div> uppercase filter is used to convert the input to all uppercase. In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all uppercase letters. <div> The name of this Tutorial is {{TutorialName}} The first Topic is {{appList[0] | uppercase}} The second Topic is {{appList[1] | uppercase}} The third Topic is {{appList[2]| uppercase}} </div> slice filter is used to slice a piece of data from the input string. In below example, we've added slice filter to an expression using pipe character. Here property value will be sliced based on the start and end positions. <div> The name of this Tutorial is {{TutorialName}} The first Topic is {{appList[0] | slice:1:2}} The second Topic is {{appList[1] | slice:1:3}} The third Topic is {{appList[2]| slice:2:3}} </div> date filter is used to convert the input string to date format. In below example, we've added date filter to an expression using pipe character. Here property value will be converted to date format. <div> The date of this Tutorial is {{newdate | date:"MM/dd/yy"}} </div> currency filter is used to convert the input string to currency format. In below example, we've added currency filter to an expression using pipe character. Here property value will be converted to currency format. <div> The currency of this Tutorial is {{newValue | currency}} </div> percent filter is used to convert the input string to percentage format. In below example, we've added percent filter to an expression using pipe character. Here property value will be converted to percentage format. <div> The percentage of this Tutorial is {{newValue | percent}} </div> When the value of a data bound property changes, then this method is called. This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens. This is for the detection and to act on changes that Angular can't or won't detect on its own. This is called in response after Angular projects external content into the component's view. This is called in response after Angular checks the content projected into the component. This is called in response after Angular initializes the component's views and child views. This is called in response after Angular checks the component's views and child views. This is the cleanup phase just before Angular destroys the directive/component. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2739, "s": 2297, "text": "Dear readers, these Angular 2 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Angular 2. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 2913, "s": 2739, "text": "AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework." }, { "code": null, "e": 3186, "s": 2913, "text": "Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time." }, { "code": null, "e": 3459, "s": 3186, "text": "Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time." }, { "code": null, "e": 3590, "s": 3459, "text": "TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft." }, { "code": null, "e": 3721, "s": 3590, "text": "TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft." }, { "code": null, "e": 3985, "s": 3721, "text": "Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications." }, { "code": null, "e": 4249, "s": 3985, "text": "Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications." }, { "code": null, "e": 4290, "s": 4249, "text": "Angular 2 has the following components −" }, { "code": null, "e": 4437, "s": 4290, "text": "Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task." }, { "code": null, "e": 4584, "s": 4437, "text": "Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task." }, { "code": null, "e": 4644, "s": 4584, "text": "Component − This can be used to bring the modules together." }, { "code": null, "e": 4704, "s": 4644, "text": "Component − This can be used to bring the modules together." }, { "code": null, "e": 4779, "s": 4704, "text": "Templates − This is used to define the views of an Angular JS application." }, { "code": null, "e": 4854, "s": 4779, "text": "Templates − This is used to define the views of an Angular JS application." }, { "code": null, "e": 4923, "s": 4854, "text": "Metadata − This can be used to add more data to an Angular JS class." }, { "code": null, "e": 4992, "s": 4923, "text": "Metadata − This can be used to add more data to an Angular JS class." }, { "code": null, "e": 5087, "s": 4992, "text": "Service − This is used to create components which can be shared across the entire application." }, { "code": null, "e": 5182, "s": 5087, "text": "Service − This is used to create components which can be shared across the entire application." }, { "code": null, "e": 5469, "s": 5182, "text": "Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. A module is made up of the following parts −" }, { "code": null, "e": 5776, "s": 5469, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 6083, "s": 5776, "text": "Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application." }, { "code": null, "e": 6196, "s": 6083, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 6309, "s": 6196, "text": "Export array − This is used to export components, directives, and pipes which can then be used in other modules." }, { "code": null, "e": 6440, "s": 6309, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 6571, "s": 6440, "text": "Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules." }, { "code": null, "e": 6849, "s": 6571, "text": "Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components.Following is the anatomy of a Component. A component consists of −" }, { "code": null, "e": 6930, "s": 6849, "text": "Class − This is like a C or Java class which consists of properties and methods." }, { "code": null, "e": 7011, "s": 6930, "text": "Class − This is like a C or Java class which consists of properties and methods." }, { "code": null, "e": 7100, "s": 7011, "text": "Metadata − This is used to decorate the class and extend the functionality of the class." }, { "code": null, "e": 7189, "s": 7100, "text": "Metadata − This is used to decorate the class and extend the functionality of the class." }, { "code": null, "e": 7276, "s": 7189, "text": "Template − This is used to define the HTML view which is displayed in the application." }, { "code": null, "e": 7363, "s": 7276, "text": "Template − This is used to define the HTML view which is displayed in the application." }, { "code": null, "e": 7534, "s": 7363, "text": "A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module." }, { "code": null, "e": 7811, "s": 7534, "text": "ngIf − The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code.\nSyntax\n*ngIf = 'expression' \n\nIf the expression evaluates to true then the corresponding gets added, else the elements are not added.\n" }, { "code": null, "e": 7819, "s": 7811, "text": "ngIf − " }, { "code": null, "e": 7954, "s": 7819, "text": "The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code." }, { "code": null, "e": 7977, "s": 7954, "text": "*ngIf = 'expression' \n" }, { "code": null, "e": 8081, "s": 7977, "text": "If the expression evaluates to true then the corresponding gets added, else the elements are not added." }, { "code": null, "e": 8297, "s": 8081, "text": "ngFor − The ngFor element is used to elements based on the condition of the For loop.\nSyntax\n*ngFor = 'let variable of variablelist' \n\nThe variable is a temporary variable to display the values in the variablelist.\n" }, { "code": null, "e": 8306, "s": 8297, "text": "ngFor − " }, { "code": null, "e": 8384, "s": 8306, "text": "The ngFor element is used to elements based on the condition of the For loop." }, { "code": null, "e": 8426, "s": 8384, "text": "*ngFor = 'let variable of variablelist' \n" }, { "code": null, "e": 8506, "s": 8426, "text": "The variable is a temporary variable to display the values in the variablelist." }, { "code": null, "e": 8651, "s": 8506, "text": "Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function." }, { "code": null, "e": 8717, "s": 8651, "text": "The catch function contains a link to the Error Handler function." }, { "code": null, "e": 8783, "s": 8717, "text": "The catch function contains a link to the Error Handler function." }, { "code": null, "e": 8933, "s": 8783, "text": "In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue." }, { "code": null, "e": 9083, "s": 8933, "text": "In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue." }, { "code": null, "e": 9173, "s": 9083, "text": "Now, whenever you get an error it will be redirected to the error console of the browser." }, { "code": null, "e": 9263, "s": 9173, "text": "Now, whenever you get an error it will be redirected to the error console of the browser." }, { "code": null, "e": 9466, "s": 9263, "text": "Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user." }, { "code": null, "e": 9620, "s": 9466, "text": "Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application." }, { "code": null, "e": 9793, "s": 9620, "text": "Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection." }, { "code": null, "e": 9976, "s": 9793, "text": "Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module." }, { "code": null, "e": 10023, "s": 9976, "text": "@Injectable() \n export class classname { \n}" }, { "code": null, "e": 10182, "s": 10023, "text": "Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator." }, { "code": null, "e": 10229, "s": 10182, "text": "@Component ({ \n providers : [classname] \n})" }, { "code": null, "e": 10317, "s": 10229, "text": "This file is used to give the options about TypeScript used for the Angular JS project." }, { "code": null, "e": 10655, "s": 10317, "text": "{ \n \"compilerOptions\": { \n \"target\": \"es5\", \n \"module\": \"commonjs\", \n \"moduleResolution\": \"node\", \n \"sourceMap\": true, \n \"emitDecoratorMetadata\": true, \n \"experimentalDecorators\": true, \n \"lib\": [ \"es2015\", \"dom\" ], \n \"noImplicitAny\": true, \n \"suppressImplicitAnyIndexErrors\": true \n } \n}" }, { "code": null, "e": 10715, "s": 10655, "text": "Following are some key points to note about the above code." }, { "code": null, "e": 10823, "s": 10715, "text": "The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript." }, { "code": null, "e": 10931, "s": 10823, "text": "The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript." }, { "code": null, "e": 11082, "s": 10931, "text": "The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true." }, { "code": null, "e": 11233, "s": 11082, "text": "The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true." }, { "code": null, "e": 11399, "s": 11233, "text": "The \"emitDecoratorMetadata\": true and \"experimentalDecorators\": true is required for Angular JS decorators. If not in place, Angular JS application will not compile." }, { "code": null, "e": 11565, "s": 11399, "text": "The \"emitDecoratorMetadata\": true and \"experimentalDecorators\": true is required for Angular JS decorators. If not in place, Angular JS application will not compile." }, { "code": null, "e": 11669, "s": 11565, "text": "This file contains information about Angular 2 project. Following are the typical settings in the file." }, { "code": null, "e": 13856, "s": 11669, "text": "{ \n \"name\": \"angular-quickstart\", \n \"version\": \"1.0.0\", \n \"description\": \"QuickStart package.json from the documentation, \n supplemented with testing support\", \n \n \"scripts\": { \n \"build\": \"tsc -p src/\", \n \"build:watch\": \"tsc -p src/ -w\", \n \"build:e2e\": \"tsc -p e2e/\", \n \"serve\": \"lite-server -c=bs-config.json\", \n \"serve:e2e\": \"lite-server -c=bs-config.e2e.json\", \n \"prestart\": \"npm run build\", \n \"start\": \"concurrently \\\"npm run build:watch\\\" \\\"npm run serve\\\"\", \n \"pree2e\": \"npm run build:e2e\", \n \"e2e\": \"concurrently \\\"npm run serve:e2e\\\" \\\"npm run protractor\\\" --killothers --success first\", \n \"preprotractor\": \"webdriver-manager update\", \n \"protractor\": \"protractor protractor.config.js\", \n \"pretest\": \"npm run build\", \n \"test\": \"concurrently \\\"npm run build:watch\\\" \\\"karma start karma.conf.js\\\"\", \n \"pretest:once\": \"npm run build\", \n \"test:once\": \"karma start karma.conf.js --single-run\", \n \"lint\": \"tslint ./src/**/*.ts -t verbose\" \n }, \n \n \"keywords\": [], \n \"author\": \"\", \n \"license\": \"MIT\", \n \"dependencies\": { \n \"@angular/common\": \"<2.4.0\", \n \"@angular/compiler\": \"<2.4.0\", \n \"@angular/core\": \"<2.4.0\",\n \"@angular/forms\": \"<2.4.0\", \n \"@angular/http\": \"<2.4.0\", \n \"@angular/platform-browser\": \"<2.4.0\", \n \"@angular/platform-browser-dynamic\": \"<2.4.0\", \n \"@angular/router\": \"<3.4.0\", \n \"angular-in-memory-web-api\": <0.2.4\", \n \"systemjs\": \"0.19.40\", \n \"core-js\": \"^2.4.1\", \n \"rxjs\": \"5.0.1\", \n \"zone.js\": \"^0.7.4\" \n }, \n \n \"devDependencies\": { \n \"concurrently\": \"^3.2.0\", \n \"lite-server\": \"^2.2.2\", \n \"typescript\": \"<2.0.10\", \n \"canonical-path\": \"0.0.2\", \n \"tslint\": \"^3.15.1\", \n \"lodash\": \"^4.16.4\", \n \"jasmine-core\": \"<2.4.1\", \n \"karma\": \"^1.3.0\", \n \"karma-chrome-launcher\": \"^2.0.0\", \n \"karma-cli\": \"^1.0.1\", \n \"karma-jasmine\": \"^1.0.2\", \n \"karma-jasmine-html-reporter\": \"^0.2.2\", \n \"protractor\": <4.0.14\", \n \"rimraf\": \"^2.5.4\", \n \"@types/node\": \"^6.0.46\", \n \"@types/jasmine\": \"2.5.36\" \n }, \n \"repository\": {} \n}" }, { "code": null, "e": 13903, "s": 13856, "text": "Some key points to note about the above code −" }, { "code": null, "e": 14110, "s": 13903, "text": "There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application." }, { "code": null, "e": 14317, "s": 14110, "text": "There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application." }, { "code": null, "e": 14461, "s": 14317, "text": "The \"build:watch\": \"tsc -p src/ -w\" command is used to compile the typescript in the background by looking for changes in the typescript files." }, { "code": null, "e": 14605, "s": 14461, "text": "The \"build:watch\": \"tsc -p src/ -w\" command is used to compile the typescript in the background by looking for changes in the typescript files." }, { "code": null, "e": 14824, "s": 14605, "text": "This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code." }, { "code": null, "e": 16384, "s": 14824, "text": "/** \n * System configuration for Angular samples \n * Adjust as necessary for your application needs. \n*/ \n(function (global) { \n System.config({ \n paths: { \n // paths serve as alias \n 'npm:': 'node_modules/' \n }, \n \n // map tells the System loader where to look for things \n map: { \n // our app is within the app folder \n app: 'app', \n \n // angular bundles \n '@angular/core': 'npm:@angular/core/bundles/core.umd.js', \n '@angular/common': 'npm:@angular/common/bundles/common.umd.js', \n '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', \n '@angular/platform-browser': 'npm:@angular/platformbrowser/bundles/platform-browser.umd.js', \n '@angular/platform-browser-dynamic': 'npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js', \n '@angular/http': 'npm:@angular/http/bundles/http.umd.js', \n '@angular/router': 'npm:@angular/router/bundles/router.umd.js', \n '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', \n \n // other libraries \n 'rxjs': 'npm:rxjs', \n 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js' \n }, \n \n // packages tells the System loader how to load when no filename and/or no extension \n packages: { \n app: { \n defaultExtension: 'js' \n }, \n rxjs: { \n defaultExtension: 'js' \n } \n } \n }); \n})(this); " }, { "code": null, "e": 16431, "s": 16384, "text": "Some key points to note about the above code −" }, { "code": null, "e": 16528, "s": 16431, "text": "'npm:': 'node_modules/' tells the location in our project where all the npm modules are located." }, { "code": null, "e": 16625, "s": 16528, "text": "'npm:': 'node_modules/' tells the location in our project where all the npm modules are located." }, { "code": null, "e": 16713, "s": 16625, "text": "The mapping of app: 'app' tells the folder where all our applications files are loaded." }, { "code": null, "e": 16801, "s": 16713, "text": "The mapping of app: 'app' tells the folder where all our applications files are loaded." }, { "code": null, "e": 16863, "s": 16801, "text": "The following code will be present in the app.module.ts file." }, { "code": null, "e": 17177, "s": 16863, "text": "import { NgModule } from '@angular/core'; \nimport { BrowserModule } from '@angular/platform-browser'; \nimport { AppComponent } from './app.component'; \n\n@NgModule({ \n imports: [ BrowserModule ], \n declarations: [ AppComponent ], \n bootstrap: [ AppComponent ] \n}) \nexport class AppModule { } " }, { "code": null, "e": 17227, "s": 17177, "text": "Let's go through each line of the code in detail." }, { "code": null, "e": 17426, "s": 17227, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 17625, "s": 17426, "text": "The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module." }, { "code": null, "e": 17729, "s": 17625, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 17833, "s": 17729, "text": "The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options." }, { "code": null, "e": 17913, "s": 17833, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 17993, "s": 17913, "text": "The BrowserModule is required by default for any web based angular application." }, { "code": null, "e": 18077, "s": 17993, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 18161, "s": 18077, "text": "The bootstrap option tells Angular which Component to bootstrap in the application." }, { "code": null, "e": 18225, "s": 18161, "text": "lowercase filter is used to convert the input to all lowercase." }, { "code": null, "e": 18393, "s": 18225, "text": "In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters." }, { "code": null, "e": 18609, "s": 18393, "text": "<div> \n The name of this Tutorial is {{TutorialName}} \n The first Topic is {{appList[0] | lowercase}} \n The second Topic is {{appList[1] | lowercase}} \n The third Topic is {{appList[2]| lowercase}} \n</div> " }, { "code": null, "e": 18673, "s": 18609, "text": "uppercase filter is used to convert the input to all uppercase." }, { "code": null, "e": 18841, "s": 18673, "text": "In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all uppercase letters." }, { "code": null, "e": 19057, "s": 18841, "text": "<div> \n The name of this Tutorial is {{TutorialName}} \n The first Topic is {{appList[0] | uppercase}} \n The second Topic is {{appList[1] | uppercase}} \n The third Topic is {{appList[2]| uppercase}} \n</div> " }, { "code": null, "e": 19126, "s": 19057, "text": "slice filter is used to slice a piece of data from the input string." }, { "code": null, "e": 19281, "s": 19126, "text": "In below example, we've added slice filter to an expression using pipe character. Here property value will be sliced based on the start and end positions." }, { "code": null, "e": 19497, "s": 19281, "text": "<div> \n The name of this Tutorial is {{TutorialName}} \n The first Topic is {{appList[0] | slice:1:2}} \n The second Topic is {{appList[1] | slice:1:3}} \n The third Topic is {{appList[2]| slice:2:3}} \n</div> " }, { "code": null, "e": 19561, "s": 19497, "text": "date filter is used to convert the input string to date format." }, { "code": null, "e": 19696, "s": 19561, "text": "In below example, we've added date filter to an expression using pipe character. Here property value will be converted to date format." }, { "code": null, "e": 19773, "s": 19696, "text": "<div> \n The date of this Tutorial is {{newdate | date:\"MM/dd/yy\"}}\n</div> " }, { "code": null, "e": 19845, "s": 19773, "text": "currency filter is used to convert the input string to currency format." }, { "code": null, "e": 19988, "s": 19845, "text": "In below example, we've added currency filter to an expression using pipe character. Here property value will be converted to currency format." }, { "code": null, "e": 20063, "s": 19988, "text": "<div> \n The currency of this Tutorial is {{newValue | currency}}\n</div> " }, { "code": null, "e": 20136, "s": 20063, "text": "percent filter is used to convert the input string to percentage format." }, { "code": null, "e": 20280, "s": 20136, "text": "In below example, we've added percent filter to an expression using pipe character. Here property value will be converted to percentage format." }, { "code": null, "e": 20356, "s": 20280, "text": "<div> \n The percentage of this Tutorial is {{newValue | percent}}\n</div> " }, { "code": null, "e": 20433, "s": 20356, "text": "When the value of a data bound property changes, then this method is called." }, { "code": null, "e": 20567, "s": 20433, "text": "This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens." }, { "code": null, "e": 20662, "s": 20567, "text": "This is for the detection and to act on changes that Angular can't or won't detect on its own." }, { "code": null, "e": 20756, "s": 20662, "text": "This is called in response after Angular projects external content into the component's view." }, { "code": null, "e": 20846, "s": 20756, "text": "This is called in response after Angular checks the content projected into the component." }, { "code": null, "e": 20938, "s": 20846, "text": "This is called in response after Angular initializes the component's views and child views." }, { "code": null, "e": 21025, "s": 20938, "text": "This is called in response after Angular checks the component's views and child views." }, { "code": null, "e": 21105, "s": 21025, "text": "This is the cleanup phase just before Angular destroys the directive/component." }, { "code": null, "e": 21140, "s": 21105, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 21154, "s": 21140, "text": " Anadi Sharma" }, { "code": null, "e": 21189, "s": 21154, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 21203, "s": 21189, "text": " Anadi Sharma" }, { "code": null, "e": 21238, "s": 21203, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 21258, "s": 21238, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 21293, "s": 21258, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 21310, "s": 21293, "text": " Frahaan Hussain" }, { "code": null, "e": 21343, "s": 21310, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 21355, "s": 21343, "text": " Senol Atac" }, { "code": null, "e": 21390, "s": 21355, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 21402, "s": 21390, "text": " Senol Atac" }, { "code": null, "e": 21409, "s": 21402, "text": " Print" }, { "code": null, "e": 21420, "s": 21409, "text": " Add Notes" } ]
Extract particular element in MongoDB within a Nested Array?
To extract the particular element in MongoDB, you can use $elemMatch operator. Let us first create a collection with documents − > db.particularElementDemo.insertOne( { "GroupId" :"Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] } ); { "acknowledged" : true, "insertedId" : 100 } > db.particularElementDemo.find().pretty(); { "_id" : 100, "GroupId" : "Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] } Display all documents from a collection with the help of find() method − > db.particularElementDemo.find().pretty(); This will produce the following output − { "_id" : 100, "GroupId" : "Group-1", "UserDetails" : [ { "UserName" : "John", "UserOtherDetails" : [ { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserEmailId" : "[email protected]", "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] } Following is the query to extract particular element in MongoDB in nested arrays − > db.particularElementDemo.find( { 'UserDetails':{ $elemMatch:{ 'UserOtherDetails':{ $elemMatch:{ 'UserFriendName':{ $elemMatch: {"Name" : "Robert" } } } } } } },{"UserDetails.UserOtherDetails.UserFriendName.Name":1} ); This will produce the following output − { "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }
[ { "code": null, "e": 1191, "s": 1062, "text": "To extract the particular element in MongoDB, you can use $elemMatch operator. Let us first create a collection with documents −" }, { "code": null, "e": 2555, "s": 1191, "text": "> db.particularElementDemo.insertOne(\n {\n \"GroupId\" :\"Group-1\",\n \"UserDetails\" : [\n {\n \"UserName\" : \"John\",\n \"UserOtherDetails\" : [\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Chris\"\n }\n ]\n },\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Robert\"\n }\n ]\n }\n ]\n }\n ]\n }\n);\n{ \"acknowledged\" : true, \"insertedId\" : 100 }\n> db.particularElementDemo.find().pretty();\n{\n \"_id\" : 100,\n \"GroupId\" : \"Group-1\",\n \"UserDetails\" : [\n {\n \"UserName\" : \"John\",\n \"UserOtherDetails\" : [\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Chris\"\n }\n ]\n },\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Robert\"\n }\n ]\n }\n ]\n }\n ]\n}" }, { "code": null, "e": 2628, "s": 2555, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2672, "s": 2628, "text": "> db.particularElementDemo.find().pretty();" }, { "code": null, "e": 2713, "s": 2672, "text": "This will produce the following output −" }, { "code": null, "e": 3299, "s": 2713, "text": "{\n \"_id\" : 100,\n \"GroupId\" : \"Group-1\",\n \"UserDetails\" : [\n {\n \"UserName\" : \"John\",\n \"UserOtherDetails\" : [\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Chris\"\n }\n ]\n },\n {\n \"UserEmailId\" : \"[email protected]\",\n \"UserFriendName\" : [\n {\n \"Name\" : \"Robert\"\n }\n ]\n }\n ]\n }\n ]\n}" }, { "code": null, "e": 3382, "s": 3299, "text": "Following is the query to extract particular element in MongoDB in nested arrays −" }, { "code": null, "e": 3710, "s": 3382, "text": "> db.particularElementDemo.find(\n {\n 'UserDetails':{\n $elemMatch:{\n 'UserOtherDetails':{\n $elemMatch:{\n 'UserFriendName':{ $elemMatch: {\"Name\" : \"Robert\" } }\n }\n }\n }\n }\n },{\"UserDetails.UserOtherDetails.UserFriendName.Name\":1}\n);" }, { "code": null, "e": 3751, "s": 3710, "text": "This will produce the following output −" }, { "code": null, "e": 3915, "s": 3751, "text": "{ \"_id\" : 100, \"UserDetails\" : [ { \"UserOtherDetails\" : [ { \"UserFriendName\" : [ { \"Name\" : \"Chris\" } ] }, { \"UserFriendName\" : [ { \"Name\" : \"Robert\" } ] } ] } ] }" } ]
isinf() function in C++
In this article we will be discussing the isinf() function in C++, its syntax, working and what will be its return value. isinf() is an inbuilt function in C++ which comes under header file, the function is used to check whether the variable passed in it is infinity or not, no matter if the number is negative infinity or positive infinity. If the number is infinite the function returns a non-zero value (true) and if it is not then it passes zero (false). Also if the number is NAN then also the function will return 0. bool isinf(float n); or bool isinf(double n); or bool isinf(long double n); This function accepts only one floating point number. Function returns boolean value, 0 for false(not infinity) and 1 if it is true(infinite). Live Demo #include <iostream> #include <cmath> using namespace std; int main() { float a = 0.0, b = 10.0; isinf(a/b)?cout<<"\nInfinte":cout<<"\nFinite"; //check the number is infinte or finite isinf(b/a)?cout<<"\nInfinite":cout<<"\nFinite"; } If we run the above code it will generate the following output − Finite Infinite Live Demo #include <iostream> #include <cmath> using namespace std; int main() { float a = 0.0; cout<<isinf(a); cout<<isinf(sqrt(-1.0)); } If we run the above code it will generate the following output − 0 0
[ { "code": null, "e": 1184, "s": 1062, "text": "In this article we will be discussing the isinf() function in C++, its syntax, working and what will be its return value." }, { "code": null, "e": 1585, "s": 1184, "text": "isinf() is an inbuilt function in C++ which comes under header file, the function is used to check whether the variable passed in it is infinity or not, no matter if the number is negative infinity or positive infinity. If the number is infinite the function returns a non-zero value (true) and if it is not then it passes zero (false). Also if the number is NAN then also the function will return 0." }, { "code": null, "e": 1606, "s": 1585, "text": "bool isinf(float n);" }, { "code": null, "e": 1609, "s": 1606, "text": "or" }, { "code": null, "e": 1632, "s": 1609, "text": "bool isinf(double n);\n" }, { "code": null, "e": 1635, "s": 1632, "text": "or" }, { "code": null, "e": 1662, "s": 1635, "text": "bool isinf(long double n);" }, { "code": null, "e": 1716, "s": 1662, "text": "This function accepts only one floating point number." }, { "code": null, "e": 1805, "s": 1716, "text": "Function returns boolean value, 0 for false(not infinity) and 1 if it is true(infinite)." }, { "code": null, "e": 1816, "s": 1805, "text": " Live Demo" }, { "code": null, "e": 2058, "s": 1816, "text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nint main() {\n float a = 0.0, b = 10.0;\n isinf(a/b)?cout<<\"\\nInfinte\":cout<<\"\\nFinite\"; //check the number is infinte or finite\n isinf(b/a)?cout<<\"\\nInfinite\":cout<<\"\\nFinite\";\n}" }, { "code": null, "e": 2123, "s": 2058, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2139, "s": 2123, "text": "Finite\nInfinite" }, { "code": null, "e": 2150, "s": 2139, "text": " Live Demo" }, { "code": null, "e": 2288, "s": 2150, "text": "#include <iostream>\n#include <cmath>\nusing namespace std; int main() {\n float a = 0.0;\n cout<<isinf(a);\n cout<<isinf(sqrt(-1.0));\n}" }, { "code": null, "e": 2353, "s": 2288, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2357, "s": 2353, "text": "0 0" } ]
Normality? How do we check that?. Is your data normal and how to check... | by Harshdeep Singh | Towards Data Science
Before I mention a couple of ways as to how to check normality, let me tell why “your data” being “normal” is good news. Normal distribution has certain properties which others don’t: It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models.and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions.and also the mean, median and mode are equal. It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models. and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions. and also the mean, median and mode are equal. The above mentioned properties make normal distributions more analytically appealing and solvable. But how do we check the normality? There are different tests which one could use depending upon how much data is available to you — sometimes you might have a few samples or a lot of samples and hence it depends on the situation! Before I describe the ways to check normality, let’s have an example dataset which has a normal distribution with a mean of 0.05 and variance of 0.9. >>> import numpy as np>>> mu, sigma = 0.05, 0.90>>> data = np.random.normal(mu, sigma, 10000) a.) The first kind of test could be to “compare the data” with a given distribution. Examples of such test can be: Lilliefors test (when the estimated parameters are known), Andrew-Darling test etc. We will have a look at the Lilliefors test which calculate the distance between the empirical distribution function of your data with the CDF of the reference distribution. Please note, that this is similar to the Kolmogorov-Smirnov test but with parameters estimated. >>> import statsmodels.api as sm>>> ## Return KS-distance, p-value>>> ks, p = sm.stats.lilliefors(data)>>> print(p)0.66190841161592895 Now since the p-value is higher than the threshold (generally, 0.05), we say that the null hypothesis is true. In other words, this means that data comes from the normal distribution. b.) The second kind of test would be to “look at the descriptive statistics” of your data such as the kurtosis (how the tails are different from standard normal distribution), or skewness (measuring the asymmetry around the mean), or a test which combines both kurtosis and skewness called as the omnibus test. >>> from scipy import stats>>> s, p = stats.normaltest(data)>>> print(p)0.6246248916944541 which similar to the observation we got from (a) and hence we can say that both test predict that the data is from the normal distribution. If you know of any other common ways to check the normality of the data, please mention it down in the comments. I hope you find this article interesting and useful.
[ { "code": null, "e": 293, "s": 172, "text": "Before I mention a couple of ways as to how to check normality, let me tell why “your data” being “normal” is good news." }, { "code": null, "e": 356, "s": 293, "text": "Normal distribution has certain properties which others don’t:" }, { "code": null, "e": 674, "s": 356, "text": "It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models.and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions.and also the mean, median and mode are equal." }, { "code": null, "e": 809, "s": 674, "text": "It has the infamous bell shape curve which is symmetric around the mean and makes it an appealing choice for linear regression models." }, { "code": null, "e": 948, "s": 809, "text": "and then because of the Central Limit Theorem, for large number of samples, normal distribution can approximate other known distributions." }, { "code": null, "e": 994, "s": 948, "text": "and also the mean, median and mode are equal." }, { "code": null, "e": 1093, "s": 994, "text": "The above mentioned properties make normal distributions more analytically appealing and solvable." }, { "code": null, "e": 1323, "s": 1093, "text": "But how do we check the normality? There are different tests which one could use depending upon how much data is available to you — sometimes you might have a few samples or a lot of samples and hence it depends on the situation!" }, { "code": null, "e": 1473, "s": 1323, "text": "Before I describe the ways to check normality, let’s have an example dataset which has a normal distribution with a mean of 0.05 and variance of 0.9." }, { "code": null, "e": 1567, "s": 1473, "text": ">>> import numpy as np>>> mu, sigma = 0.05, 0.90>>> data = np.random.normal(mu, sigma, 10000)" }, { "code": null, "e": 1766, "s": 1567, "text": "a.) The first kind of test could be to “compare the data” with a given distribution. Examples of such test can be: Lilliefors test (when the estimated parameters are known), Andrew-Darling test etc." }, { "code": null, "e": 2035, "s": 1766, "text": "We will have a look at the Lilliefors test which calculate the distance between the empirical distribution function of your data with the CDF of the reference distribution. Please note, that this is similar to the Kolmogorov-Smirnov test but with parameters estimated." }, { "code": null, "e": 2170, "s": 2035, "text": ">>> import statsmodels.api as sm>>> ## Return KS-distance, p-value>>> ks, p = sm.stats.lilliefors(data)>>> print(p)0.66190841161592895" }, { "code": null, "e": 2354, "s": 2170, "text": "Now since the p-value is higher than the threshold (generally, 0.05), we say that the null hypothesis is true. In other words, this means that data comes from the normal distribution." }, { "code": null, "e": 2665, "s": 2354, "text": "b.) The second kind of test would be to “look at the descriptive statistics” of your data such as the kurtosis (how the tails are different from standard normal distribution), or skewness (measuring the asymmetry around the mean), or a test which combines both kurtosis and skewness called as the omnibus test." }, { "code": null, "e": 2756, "s": 2665, "text": ">>> from scipy import stats>>> s, p = stats.normaltest(data)>>> print(p)0.6246248916944541" }, { "code": null, "e": 2896, "s": 2756, "text": "which similar to the observation we got from (a) and hence we can say that both test predict that the data is from the normal distribution." }, { "code": null, "e": 3009, "s": 2896, "text": "If you know of any other common ways to check the normality of the data, please mention it down in the comments." } ]
How to add the slider to a menu item in JavaFX?
JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider. In JavaFX you can create a slider by instantiating the javafx.scene.control.Slider class. A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class. A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it. The MenuItem class has a property named graphic this is of the type Node; this specifies the optional graphic for the current menu-item. You can set the value to this property using the setGraphic() method. To add slider as a menu item create a slider object, invoke the setGrapic() method by passing this object as a parameter. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.Slider; import javafx.scene.paint.Color; import javafx.stage.Stage; public class SliderAsMenuItem extends Application { @Override public void start(Stage stage) { //Creating a slider Slider slider = new Slider(0, 100, 0); slider.setShowTickLabels(true); slider.setShowTickMarks(true); slider.setMajorTickUnit(25); slider.setBlockIncrement(10); //Creating menu Menu fileMenu = new Menu("File"); //Creating menu item MenuItem item = new MenuItem(); //Setting slider as a menu item item.setGraphic(slider); //Adding all the menu items to the menu fileMenu.getItems().addAll(item); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(200); menuBar.setTranslateY(20); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Menu"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1377, "s": 1062, "text": "JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider." }, { "code": null, "e": 1467, "s": 1377, "text": "In JavaFX you can create a slider by instantiating the javafx.scene.control.Slider class." }, { "code": null, "e": 1653, "s": 1467, "text": "A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class." }, { "code": null, "e": 1869, "s": 1653, "text": "A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it." }, { "code": null, "e": 2076, "s": 1869, "text": "The MenuItem class has a property named graphic this is of the type Node; this specifies the optional graphic for the current menu-item. You can set the value to this property using the setGraphic() method." }, { "code": null, "e": 2198, "s": 2076, "text": "To add slider as a menu item create a slider object, invoke the setGrapic() method by passing this object as a parameter." }, { "code": null, "e": 3540, "s": 2198, "text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.control.Slider;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class SliderAsMenuItem extends Application {\n @Override\n public void start(Stage stage) {\n //Creating a slider\n Slider slider = new Slider(0, 100, 0);\n slider.setShowTickLabels(true);\n slider.setShowTickMarks(true);\n slider.setMajorTickUnit(25);\n slider.setBlockIncrement(10);\n //Creating menu\n Menu fileMenu = new Menu(\"File\");\n //Creating menu item\n MenuItem item = new MenuItem();\n //Setting slider as a menu item\n item.setGraphic(slider);\n //Adding all the menu items to the menu\n fileMenu.getItems().addAll(item);\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(fileMenu);\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Template non-type arguments in C++ - GeeksforGeeks
29 Dec, 2020 Prerequisite: Templates in C++ Generally, a C++ template, with a single argument looks like this: template<typename template_name> But it has been seen that a template can have multiple arguments. The syntax for the same would be: template<class T1, class T2, class T3, ........., class Tn> where, n is the number of arguments. It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types. Example 1: template <class T, int size> class Array { private: // Automatic array initialization T Arr[size] ..... ..... }; Explanation: In the above example, the template supplies the size of the array as an argument. This implies that the size of the array is known to the compiler at the compile time itself. The arguments must be specified whenever a template class is created. Example 2: // Array of 10 integers Array<int, 10> a1 // Array of 5 double type numbers Array<double, 5> a2 // String of size 9 Array<char, 10> a3 where size is given as an argument to the template class. Following are the arguments that are allowed: Constant Expressions Addresses of function or objects with external linkage Addresses of static class members. Below is the program to illustrate the Non-type templates: C++ // C++ program to implement bubble sort// by using Non-type as function parameters#include <iostream>using namespace std; // Function to swap two numberstemplate <class T>void swap_(T* x, T* y){ T temp = *x; *x = *y; *y = temp;} // Function to implement the Bubble Sorttemplate <class T, int size>void bubble_sort(T arr[]){ for (int i = 0; i < size - 1; i++) { // Last i elements are already // in place for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap operation swap_(&arr[j], &arr[j + 1]); } } }} // Function to print an arraytemplate <class T, int size>void printArray(T arr[]){ int i; for (i = 0; i < size - 1; i++) { cout << arr[i] << ", "; } cout << arr[size - 1] << endl;} // Driver Codeint main(){ // Given array arr[] float arr[] = { 1.1, 1.2, 0.3, 4.55, 1.56, 0.6 }; const int size_arr = sizeof(arr) / sizeof(arr[0]); // Size of the array passed as // an argument to the function bubble_sort<float, size_arr>(arr); cout << "Sorted Array is: "; printArray<float, size_arr>(arr); return 0;} Sorted Array is: 0.3, 0.6, 1.1, 1.2, 1.56, 4.55 C++-Function Overloading and Default Arguments C++-Templates Technical Scripter 2020 Templates C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Convert string to char array in C++ Destructors in C++ new and delete operators in C++ for dynamic memory Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23731, "s": 23703, "text": "\n29 Dec, 2020" }, { "code": null, "e": 23762, "s": 23731, "text": "Prerequisite: Templates in C++" }, { "code": null, "e": 23829, "s": 23762, "text": "Generally, a C++ template, with a single argument looks like this:" }, { "code": null, "e": 23862, "s": 23829, "text": "template<typename template_name>" }, { "code": null, "e": 23962, "s": 23862, "text": "But it has been seen that a template can have multiple arguments. The syntax for the same would be:" }, { "code": null, "e": 24022, "s": 23962, "text": "template<class T1, class T2, class T3, ........., class Tn>" }, { "code": null, "e": 24059, "s": 24022, "text": "where, n is the number of arguments." }, { "code": null, "e": 24286, "s": 24059, "text": "It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types." }, { "code": null, "e": 24297, "s": 24286, "text": "Example 1:" }, { "code": null, "e": 24428, "s": 24297, "text": "template <class T, int size>\nclass Array {\nprivate:\n\n // Automatic array initialization\n T Arr[size]\n .....\n .....\n};\n" }, { "code": null, "e": 24441, "s": 24428, "text": "Explanation:" }, { "code": null, "e": 24686, "s": 24441, "text": "In the above example, the template supplies the size of the array as an argument. This implies that the size of the array is known to the compiler at the compile time itself. The arguments must be specified whenever a template class is created." }, { "code": null, "e": 24697, "s": 24686, "text": "Example 2:" }, { "code": null, "e": 24897, "s": 24697, "text": "// Array of 10 integers\nArray<int, 10> a1\n\n// Array of 5 double type numbers\nArray<double, 5> a2\n\n// String of size 9 \nArray<char, 10> a3 \n\nwhere size is given as an argument to the template class.\n" }, { "code": null, "e": 24943, "s": 24897, "text": "Following are the arguments that are allowed:" }, { "code": null, "e": 24964, "s": 24943, "text": "Constant Expressions" }, { "code": null, "e": 25019, "s": 24964, "text": "Addresses of function or objects with external linkage" }, { "code": null, "e": 25054, "s": 25019, "text": "Addresses of static class members." }, { "code": null, "e": 25113, "s": 25054, "text": "Below is the program to illustrate the Non-type templates:" }, { "code": null, "e": 25117, "s": 25113, "text": "C++" }, { "code": "// C++ program to implement bubble sort// by using Non-type as function parameters#include <iostream>using namespace std; // Function to swap two numberstemplate <class T>void swap_(T* x, T* y){ T temp = *x; *x = *y; *y = temp;} // Function to implement the Bubble Sorttemplate <class T, int size>void bubble_sort(T arr[]){ for (int i = 0; i < size - 1; i++) { // Last i elements are already // in place for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap operation swap_(&arr[j], &arr[j + 1]); } } }} // Function to print an arraytemplate <class T, int size>void printArray(T arr[]){ int i; for (i = 0; i < size - 1; i++) { cout << arr[i] << \", \"; } cout << arr[size - 1] << endl;} // Driver Codeint main(){ // Given array arr[] float arr[] = { 1.1, 1.2, 0.3, 4.55, 1.56, 0.6 }; const int size_arr = sizeof(arr) / sizeof(arr[0]); // Size of the array passed as // an argument to the function bubble_sort<float, size_arr>(arr); cout << \"Sorted Array is: \"; printArray<float, size_arr>(arr); return 0;}", "e": 26300, "s": 25117, "text": null }, { "code": null, "e": 26349, "s": 26300, "text": "Sorted Array is: 0.3, 0.6, 1.1, 1.2, 1.56, 4.55\n" }, { "code": null, "e": 26396, "s": 26349, "text": "C++-Function Overloading and Default Arguments" }, { "code": null, "e": 26410, "s": 26396, "text": "C++-Templates" }, { "code": null, "e": 26434, "s": 26410, "text": "Technical Scripter 2020" }, { "code": null, "e": 26444, "s": 26434, "text": "Templates" }, { "code": null, "e": 26448, "s": 26444, "text": "C++" }, { "code": null, "e": 26467, "s": 26448, "text": "Technical Scripter" }, { "code": null, "e": 26471, "s": 26467, "text": "CPP" }, { "code": null, "e": 26569, "s": 26471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26578, "s": 26569, "text": "Comments" }, { "code": null, "e": 26591, "s": 26578, "text": "Old Comments" }, { "code": null, "e": 26619, "s": 26591, "text": "Operator Overloading in C++" }, { "code": null, "e": 26643, "s": 26619, "text": "Sorting a vector in C++" }, { "code": null, "e": 26676, "s": 26643, "text": "Friend class and function in C++" }, { "code": null, "e": 26696, "s": 26676, "text": "Polymorphism in C++" }, { "code": null, "e": 26740, "s": 26696, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26776, "s": 26740, "text": "Convert string to char array in C++" }, { "code": null, "e": 26795, "s": 26776, "text": "Destructors in C++" }, { "code": null, "e": 26846, "s": 26795, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 26890, "s": 26846, "text": "Pair in C++ Standard Template Library (STL)" } ]
Python program to check if two lists have at least one common element
In this problem we use two user input list. Our task is to check that there is any common element or not. We use very simple traversing technique, traverse both the list and check the every element of first list and second list. Input : A = [10, 20, 30, 50] B = [90, 80, 30, 10, 3] Output : FOUND Input : A = [10, 20, 30, 50] B = [100,200,300,500] Output : NOT FOUND commonelement(A,B) /* A and B are two user input list */ Step 1: First use one third variable c which is display the result. Step 2: Traverse both the list and compare every element of the first list with every element of the second list. Step 3: If common element is found then c display FOUND otherwise display NOT FOUND. # Python program to check # if two lists have at-least # one element common # using traversal of list def commonelement(A, B): c = "NOT FOUND" # traverse in the 1st list for i in A: # traverse in the 2nd list for j in B: # if one common if i == j: c="FOUND" return c return c # Driver code A=list() B=list() n1=int(input("Enter the size of the first List ::")) print("Enter the Element of first List ::") for i in range(int(n1)): k=int(input("")) A.append(k) n2=int(input("Enter the size of the second List ::")) print("Enter the Element of second List ::") for i in range(int(n2)): k=int(input("")) B.append(k) print("Display Result ::",commonelement(A, B)) Enter the size of the first List ::4 Enter the Element of first List :: 2 1 4 9 Enter the size of the second List ::5 Enter the Element of second List :: 9 90 4 89 67 Display Result :: FOUND Enter the size of the first List ::4 Enter the Element of first List :: 67 89 45 23 Enter the size of the second List ::4 Enter the Element of second List :: 1 2 3 4 Display Result :: NOT FOUND
[ { "code": null, "e": 1291, "s": 1062, "text": "In this problem we use two user input list. Our task is to check that there is any common element or not. We use very simple traversing technique, traverse both the list and check the every element of first list and second list." }, { "code": null, "e": 1446, "s": 1291, "text": "Input : A = [10, 20, 30, 50]\n B = [90, 80, 30, 10, 3]\nOutput : FOUND\nInput : A = [10, 20, 30, 50]\n B = [100,200,300,500]\nOutput : NOT FOUND\n" }, { "code": null, "e": 1771, "s": 1446, "text": "commonelement(A,B)\n/* A and B are two user input list */\nStep 1: First use one third variable c which is display the result.\nStep 2: Traverse both the list and compare every element of the first list with every element of the second list.\nStep 3: If common element is found then c display FOUND otherwise display NOT FOUND.\n" }, { "code": null, "e": 2532, "s": 1771, "text": "# Python program to check \n# if two lists have at-least \n# one element common \n# using traversal of list \n \ndef commonelement(A, B): \n c = \"NOT FOUND\"\n\n # traverse in the 1st list \n for i in A: \n # traverse in the 2nd list \n for j in B: \n # if one common \n if i == j: \n c=\"FOUND\"\n return c \n return c \n\n# Driver code\nA=list()\nB=list()\nn1=int(input(\"Enter the size of the first List ::\"))\nprint(\"Enter the Element of first List ::\")\nfor i in range(int(n1)):\n k=int(input(\"\"))\n A.append(k)\nn2=int(input(\"Enter the size of the second List ::\"))\nprint(\"Enter the Element of second List ::\")\nfor i in range(int(n2)):\n k=int(input(\"\"))\n B.append(k)\n\nprint(\"Display Result ::\",commonelement(A, B)) " }, { "code": null, "e": 2919, "s": 2532, "text": "Enter the size of the first List ::4\nEnter the Element of first List ::\n2\n1\n4\n9\nEnter the size of the second List ::5\nEnter the Element of second List ::\n9\n90\n4\n89\n67\nDisplay Result :: FOUND\n\nEnter the size of the first List ::4\nEnter the Element of first List ::\n67\n89\n45\n23\nEnter the size of the second List ::4\nEnter the Element of second List ::\n1\n2\n3\n4\nDisplay Result :: NOT FOUND\n" } ]
Java Program to Enode a Message Using Playfair Cipher - GeeksforGeeks
22 Feb, 2021 The Playfair cipher is one of the traditional ciphers which comes under the category of substitution ciphers. In Playfair Cipher, unlike traditional cipher, we encrypt a pair of alphabets (digraphs) instead of a single alphabet. In Playfair cipher, initially, a key table is created. The key table is a 5×5 matrix consisting of alphabets that acts as the key for encryption of the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually ‘j’) is omitted from the table, as we need only 25 alphabets instead of 26. If the plaintext contains ‘j’, then it is replaced by ‘i’. Process for Playfair Cipher: The plaintext message is split into pairs of two letters (digraphs). If the plaintext has an odd number of characters, append ‘z’ to the end to make the message of even length.Identify any double letters placed side by side in the plaintext and replace the second occurrence with an ‘x’ e.g. ‘hello’ -> ‘he lx lo’.Now, locate the letters in the 5×5 key table.Use the following rules for encryption of plaintext:If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column)If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter. The plaintext message is split into pairs of two letters (digraphs). If the plaintext has an odd number of characters, append ‘z’ to the end to make the message of even length. Identify any double letters placed side by side in the plaintext and replace the second occurrence with an ‘x’ e.g. ‘hello’ -> ‘he lx lo’. Now, locate the letters in the 5×5 key table. Use the following rules for encryption of plaintext:If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column)If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter. If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row). If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column) If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter. The decryption process of Playfair cipher is the same encryption process, but it is applied in a reverse manner. The receiver has the same key and can create the same key table, and he uses it to decrypt the ciphertext messages generated using that key. Example: Inputs for playfair cipher Playfair Cipher Key Matrix Ciphertext generation using Playfair Cipher Java // Java Program to Enode a Message Using Playfair Cipher import java.io.*;import java.util.*; class Playfair { String key; String plainText; char[][] matrix = new char[5][5]; public Playfair(String key, String plainText) { // convert all the characters to lowercase this.key = key.toLowerCase(); this.plainText = plainText.toLowerCase(); } // function to remove duplicate characters from the key public void cleanPlayFairKey() { LinkedHashSet<Character> set = new LinkedHashSet<Character>(); String newKey = ""; for (int i = 0; i < key.length(); i++) set.add(key.charAt(i)); Iterator<Character> it = set.iterator(); while (it.hasNext()) newKey += (Character)it.next(); key = newKey; } // function to generate playfair cipher key table public void generateCipherKey() { Set<Character> set = new HashSet<Character>(); for (int i = 0; i < key.length(); i++) { if (key.charAt(i) == 'j') continue; set.add(key.charAt(i)); } // remove repeated characters from the cipher key String tempKey = new String(key); for (int i = 0; i < 26; i++) { char ch = (char)(i + 97); if (ch == 'j') continue; if (!set.contains(ch)) tempKey += ch; } // create cipher key table for (int i = 0, idx = 0; i < 5; i++) for (int j = 0; j < 5; j++) matrix[i][j] = tempKey.charAt(idx++); System.out.println("Playfair Cipher Key Matrix:"); for (int i = 0; i < 5; i++) System.out.println(Arrays.toString(matrix[i])); } // function to preprocess plaintext public String formatPlainText() { String message = ""; int len = plainText.length(); for (int i = 0; i < len; i++) { // if plaintext contains the character 'j', // replace it with 'i' if (plainText.charAt(i) == 'j') message += 'i'; else message += plainText.charAt(i); } // if two consecutive characters are same, then // insert character 'x' in between them for (int i = 0; i < message.length(); i += 2) { if (message.charAt(i) == message.charAt(i + 1)) message = message.substring(0, i + 1) + 'x' + message.substring(i + 1); } // make the plaintext of even length if (len % 2 == 1) message += 'x'; // dummy character return message; } // function to group every two characters public String[] formPairs(String message) { int len = message.length(); String[] pairs = new String[len / 2]; for (int i = 0, cnt = 0; i < len / 2; i++) pairs[i] = message.substring(cnt, cnt += 2); return pairs; } // function to get position of character in key table public int[] getCharPos(char ch) { int[] keyPos = new int[2]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (matrix[i][j] == ch) { keyPos[0] = i; keyPos[1] = j; break; } } } return keyPos; } public String encryptMessage() { String message = formatPlainText(); String[] msgPairs = formPairs(message); String encText = ""; for (int i = 0; i < msgPairs.length; i++) { char ch1 = msgPairs[i].charAt(0); char ch2 = msgPairs[i].charAt(1); int[] ch1Pos = getCharPos(ch1); int[] ch2Pos = getCharPos(ch2); // if both the characters are in the same row if (ch1Pos[0] == ch2Pos[0]) { ch1Pos[1] = (ch1Pos[1] + 1) % 5; ch2Pos[1] = (ch2Pos[1] + 1) % 5; } // if both the characters are in the same column else if (ch1Pos[1] == ch2Pos[1]) { ch1Pos[0] = (ch1Pos[0] + 1) % 5; ch2Pos[0] = (ch2Pos[0] + 1) % 5; } // if both the characters are in different rows // and columns else { int temp = ch1Pos[1]; ch1Pos[1] = ch2Pos[1]; ch2Pos[1] = temp; } // get the corresponding cipher characters from // the key matrix encText = encText + matrix[ch1Pos[0]][ch1Pos[1]] + matrix[ch2Pos[0]][ch2Pos[1]]; } return encText; }} public class GFG { public static void main(String[] args) { System.out.println("Example-1\n"); String key1 = "Problem"; String plainText1 = "Playfair"; System.out.println("Key: " + key1); System.out.println("PlainText: " + plainText1); Playfair pfc1 = new Playfair(key1, plainText1); pfc1.cleanPlayFairKey(); pfc1.generateCipherKey(); String encText1 = pfc1.encryptMessage(); System.out.println("Cipher Text is: " + encText1); System.out.println("\nExample-2\n"); String key2 = "Problem"; String plainText2 = "Hello"; System.out.println("Key: " + key2); System.out.println("PlainText: " + plainText2); Playfair pfc2 = new Playfair(key2, plainText2); pfc2.cleanPlayFairKey(); pfc2.generateCipherKey(); String encText2 = pfc2.encryptMessage(); System.out.println("Cipher Text is: " + encText2); }} Example-1 Key: Problem PlainText: Playfair Playfair Cipher Key Matrix: [p, r, o, b, l] [e, m, a, c, d] [f, g, h, i, k] [n, q, s, t, u] [v, w, x, y, z] Cipher Text is: rpcxhegb Example-2 Key: Problem PlainText: Hello Playfair Cipher Key Matrix: [p, r, o, b, l] [e, m, a, c, d] [f, g, h, i, k] [n, q, s, t, u] [v, w, x, y, z] Cipher Text is: faozpb Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24760, "s": 24732, "text": "\n22 Feb, 2021" }, { "code": null, "e": 25367, "s": 24760, "text": "The Playfair cipher is one of the traditional ciphers which comes under the category of substitution ciphers. In Playfair Cipher, unlike traditional cipher, we encrypt a pair of alphabets (digraphs) instead of a single alphabet. In Playfair cipher, initially, a key table is created. The key table is a 5×5 matrix consisting of alphabets that acts as the key for encryption of the plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually ‘j’) is omitted from the table, as we need only 25 alphabets instead of 26. If the plaintext contains ‘j’, then it is replaced by ‘i’." }, { "code": null, "e": 25396, "s": 25367, "text": "Process for Playfair Cipher:" }, { "code": null, "e": 26415, "s": 25396, "text": "The plaintext message is split into pairs of two letters (digraphs). If the plaintext has an odd number of characters, append ‘z’ to the end to make the message of even length.Identify any double letters placed side by side in the plaintext and replace the second occurrence with an ‘x’ e.g. ‘hello’ -> ‘he lx lo’.Now, locate the letters in the 5×5 key table.Use the following rules for encryption of plaintext:If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column)If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter." }, { "code": null, "e": 26592, "s": 26415, "text": "The plaintext message is split into pairs of two letters (digraphs). If the plaintext has an odd number of characters, append ‘z’ to the end to make the message of even length." }, { "code": null, "e": 26731, "s": 26592, "text": "Identify any double letters placed side by side in the plaintext and replace the second occurrence with an ‘x’ e.g. ‘hello’ -> ‘he lx lo’." }, { "code": null, "e": 26777, "s": 26731, "text": "Now, locate the letters in the 5×5 key table." }, { "code": null, "e": 27437, "s": 26777, "text": "Use the following rules for encryption of plaintext:If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column)If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter." }, { "code": null, "e": 27671, "s": 27437, "text": "If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row)." }, { "code": null, "e": 27906, "s": 27671, "text": "If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column)" }, { "code": null, "e": 28047, "s": 27906, "text": "If the letters are not on the same row or column, replace them with the letters in their own row but in the same column as the other letter." }, { "code": null, "e": 28301, "s": 28047, "text": "The decryption process of Playfair cipher is the same encryption process, but it is applied in a reverse manner. The receiver has the same key and can create the same key table, and he uses it to decrypt the ciphertext messages generated using that key." }, { "code": null, "e": 28310, "s": 28301, "text": "Example:" }, { "code": null, "e": 28337, "s": 28310, "text": "Inputs for playfair cipher" }, { "code": null, "e": 28364, "s": 28337, "text": "Playfair Cipher Key Matrix" }, { "code": null, "e": 28408, "s": 28364, "text": "Ciphertext generation using Playfair Cipher" }, { "code": null, "e": 28413, "s": 28408, "text": "Java" }, { "code": "// Java Program to Enode a Message Using Playfair Cipher import java.io.*;import java.util.*; class Playfair { String key; String plainText; char[][] matrix = new char[5][5]; public Playfair(String key, String plainText) { // convert all the characters to lowercase this.key = key.toLowerCase(); this.plainText = plainText.toLowerCase(); } // function to remove duplicate characters from the key public void cleanPlayFairKey() { LinkedHashSet<Character> set = new LinkedHashSet<Character>(); String newKey = \"\"; for (int i = 0; i < key.length(); i++) set.add(key.charAt(i)); Iterator<Character> it = set.iterator(); while (it.hasNext()) newKey += (Character)it.next(); key = newKey; } // function to generate playfair cipher key table public void generateCipherKey() { Set<Character> set = new HashSet<Character>(); for (int i = 0; i < key.length(); i++) { if (key.charAt(i) == 'j') continue; set.add(key.charAt(i)); } // remove repeated characters from the cipher key String tempKey = new String(key); for (int i = 0; i < 26; i++) { char ch = (char)(i + 97); if (ch == 'j') continue; if (!set.contains(ch)) tempKey += ch; } // create cipher key table for (int i = 0, idx = 0; i < 5; i++) for (int j = 0; j < 5; j++) matrix[i][j] = tempKey.charAt(idx++); System.out.println(\"Playfair Cipher Key Matrix:\"); for (int i = 0; i < 5; i++) System.out.println(Arrays.toString(matrix[i])); } // function to preprocess plaintext public String formatPlainText() { String message = \"\"; int len = plainText.length(); for (int i = 0; i < len; i++) { // if plaintext contains the character 'j', // replace it with 'i' if (plainText.charAt(i) == 'j') message += 'i'; else message += plainText.charAt(i); } // if two consecutive characters are same, then // insert character 'x' in between them for (int i = 0; i < message.length(); i += 2) { if (message.charAt(i) == message.charAt(i + 1)) message = message.substring(0, i + 1) + 'x' + message.substring(i + 1); } // make the plaintext of even length if (len % 2 == 1) message += 'x'; // dummy character return message; } // function to group every two characters public String[] formPairs(String message) { int len = message.length(); String[] pairs = new String[len / 2]; for (int i = 0, cnt = 0; i < len / 2; i++) pairs[i] = message.substring(cnt, cnt += 2); return pairs; } // function to get position of character in key table public int[] getCharPos(char ch) { int[] keyPos = new int[2]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (matrix[i][j] == ch) { keyPos[0] = i; keyPos[1] = j; break; } } } return keyPos; } public String encryptMessage() { String message = formatPlainText(); String[] msgPairs = formPairs(message); String encText = \"\"; for (int i = 0; i < msgPairs.length; i++) { char ch1 = msgPairs[i].charAt(0); char ch2 = msgPairs[i].charAt(1); int[] ch1Pos = getCharPos(ch1); int[] ch2Pos = getCharPos(ch2); // if both the characters are in the same row if (ch1Pos[0] == ch2Pos[0]) { ch1Pos[1] = (ch1Pos[1] + 1) % 5; ch2Pos[1] = (ch2Pos[1] + 1) % 5; } // if both the characters are in the same column else if (ch1Pos[1] == ch2Pos[1]) { ch1Pos[0] = (ch1Pos[0] + 1) % 5; ch2Pos[0] = (ch2Pos[0] + 1) % 5; } // if both the characters are in different rows // and columns else { int temp = ch1Pos[1]; ch1Pos[1] = ch2Pos[1]; ch2Pos[1] = temp; } // get the corresponding cipher characters from // the key matrix encText = encText + matrix[ch1Pos[0]][ch1Pos[1]] + matrix[ch2Pos[0]][ch2Pos[1]]; } return encText; }} public class GFG { public static void main(String[] args) { System.out.println(\"Example-1\\n\"); String key1 = \"Problem\"; String plainText1 = \"Playfair\"; System.out.println(\"Key: \" + key1); System.out.println(\"PlainText: \" + plainText1); Playfair pfc1 = new Playfair(key1, plainText1); pfc1.cleanPlayFairKey(); pfc1.generateCipherKey(); String encText1 = pfc1.encryptMessage(); System.out.println(\"Cipher Text is: \" + encText1); System.out.println(\"\\nExample-2\\n\"); String key2 = \"Problem\"; String plainText2 = \"Hello\"; System.out.println(\"Key: \" + key2); System.out.println(\"PlainText: \" + plainText2); Playfair pfc2 = new Playfair(key2, plainText2); pfc2.cleanPlayFairKey(); pfc2.generateCipherKey(); String encText2 = pfc2.encryptMessage(); System.out.println(\"Cipher Text is: \" + encText2); }}", "e": 34343, "s": 28413, "text": null }, { "code": null, "e": 34693, "s": 34343, "text": "Example-1\n\nKey: Problem\nPlainText: Playfair\nPlayfair Cipher Key Matrix:\n[p, r, o, b, l]\n[e, m, a, c, d]\n[f, g, h, i, k]\n[n, q, s, t, u]\n[v, w, x, y, z]\nCipher Text is: rpcxhegb\n\nExample-2\n\nKey: Problem\nPlainText: Hello\nPlayfair Cipher Key Matrix:\n[p, r, o, b, l]\n[e, m, a, c, d]\n[f, g, h, i, k]\n[n, q, s, t, u]\n[v, w, x, y, z]\nCipher Text is: faozpb" }, { "code": null, "e": 34700, "s": 34693, "text": "Picked" }, { "code": null, "e": 34724, "s": 34700, "text": "Technical Scripter 2020" }, { "code": null, "e": 34729, "s": 34724, "text": "Java" }, { "code": null, "e": 34743, "s": 34729, "text": "Java Programs" }, { "code": null, "e": 34762, "s": 34743, "text": "Technical Scripter" }, { "code": null, "e": 34767, "s": 34762, "text": "Java" }, { "code": null, "e": 34865, "s": 34767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34880, "s": 34865, "text": "Stream In Java" }, { "code": null, "e": 34931, "s": 34880, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 34961, "s": 34931, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34980, "s": 34961, "text": "Interfaces in Java" }, { "code": null, "e": 35011, "s": 34980, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35039, "s": 35011, "text": "Initializing a List in Java" }, { "code": null, "e": 35083, "s": 35039, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 35109, "s": 35083, "text": "Java Programming Examples" }, { "code": null, "e": 35143, "s": 35109, "text": "Convert Double to Integer in Java" } ]
Can We Override Default Method in Java? - GeeksforGeeks
05 Feb, 2021 Default method in Java is a method in java which are defined inside the interface with the keyword default is known as the default method. It is a type of non-abstract method. This method is capable of adding backward capability so that the old interface can grasp the lambda expression capability. Java Interface Default method is also known as Defender Method or virtual extension method. Interfaces could have only abstract methods before Java 8. The classes separately provide implementation to these methods. So, if a new method is to be added to an interface, then its implementation code has to be provided in the class implementing the same interface. For overcoming this issue, Java 8 introduced the concept of default methods that allow the interfaces to have methods with implementation without affecting the classes that implement the interface. Can We Override Default Method in Java? It is not mandatory to override the default method in Java. If we are using Only one interface in a Program then at a time we are using only a single default method and at that time Overriding is not required as shown in the below program: Java // Creating Interfaceinterface GfG{ public default void display() { System.out.println("GEEKSFORGEEKS"); }} // Main Class With Implementation Of Interfacepublic class InterfaceExample implements GfG{ public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); // Calling Interface obj.display(); }} GEEKSFORGEEKS But when more than two Interfaces are used and both act as parent class then at that time Overriding of the Default Method is required. If we are using more than one interface and in both interfaces, if both interfaces have the same name and same structure. So at that time, one must override either one both the default method otherwise it will result in an error. Case 1: When Two Interfaces are not overridden Java // Java program to demonstrate the case when // two interfaces are not overridden // Creating Interface Oneinterface GfG{ public default void display() { System.out.println("GEEKSFORGEEKS"); }} // Creating Interface Twointerface gfg{ public default void display() { System.out.println("geeksforgeeks"); }} // Interfaces are not Overidden public class InterfaceExample implements GfG,gfg { public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); }} Output: InterfaceExample.java:18: error: types GfG and gfg are incompatible; public class InterfaceExample implements GfG,gfg { ^ class InterfaceExample inherits unrelated defaults for display() from types GfG and gfg 1 error Case 2: When Two Interfaces are Overridden Java // Java program to demonstrate the case// when two interfaces are overridden // Creating Interface Oneinterface GfG{ public default void display() { System.out.println("GEEKSFORGEEKS"); }} // Creating Interface Twointerface gfg{ public default void display() { System.out.println("geeksforgeeks"); }} public class InterfaceExample implements GfG,gfg { // Interfaces are Overridedpublic void display() { GfG.super.display(); gfg.super.display(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); }} GEEKSFORGEEKS geeksforgeeks Java 8 java-overriding Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java LinkedList in Java Stack Class in Java Overriding in Java
[ { "code": null, "e": 24135, "s": 24107, "text": "\n05 Feb, 2021" }, { "code": null, "e": 24312, "s": 24135, "text": "Default method in Java is a method in java which are defined inside the interface with the keyword default is known as the default method. It is a type of non-abstract method. " }, { "code": null, "e": 24435, "s": 24312, "text": "This method is capable of adding backward capability so that the old interface can grasp the lambda expression capability." }, { "code": null, "e": 24527, "s": 24435, "text": "Java Interface Default method is also known as Defender Method or virtual extension method." }, { "code": null, "e": 24995, "s": 24527, "text": "Interfaces could have only abstract methods before Java 8. The classes separately provide implementation to these methods. So, if a new method is to be added to an interface, then its implementation code has to be provided in the class implementing the same interface. For overcoming this issue, Java 8 introduced the concept of default methods that allow the interfaces to have methods with implementation without affecting the classes that implement the interface. " }, { "code": null, "e": 25035, "s": 24995, "text": "Can We Override Default Method in Java?" }, { "code": null, "e": 25096, "s": 25035, "text": "It is not mandatory to override the default method in Java. " }, { "code": null, "e": 25276, "s": 25096, "text": "If we are using Only one interface in a Program then at a time we are using only a single default method and at that time Overriding is not required as shown in the below program:" }, { "code": null, "e": 25281, "s": 25276, "text": "Java" }, { "code": "// Creating Interfaceinterface GfG{ public default void display() { System.out.println(\"GEEKSFORGEEKS\"); }} // Main Class With Implementation Of Interfacepublic class InterfaceExample implements GfG{ public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); // Calling Interface obj.display(); }}", "e": 25648, "s": 25281, "text": null }, { "code": null, "e": 25662, "s": 25648, "text": "GEEKSFORGEEKS" }, { "code": null, "e": 26028, "s": 25662, "text": "But when more than two Interfaces are used and both act as parent class then at that time Overriding of the Default Method is required. If we are using more than one interface and in both interfaces, if both interfaces have the same name and same structure. So at that time, one must override either one both the default method otherwise it will result in an error." }, { "code": null, "e": 26075, "s": 26028, "text": "Case 1: When Two Interfaces are not overridden" }, { "code": null, "e": 26080, "s": 26075, "text": "Java" }, { "code": "// Java program to demonstrate the case when // two interfaces are not overridden // Creating Interface Oneinterface GfG{ public default void display() { System.out.println(\"GEEKSFORGEEKS\"); }} // Creating Interface Twointerface gfg{ public default void display() { System.out.println(\"geeksforgeeks\"); }} // Interfaces are not Overidden public class InterfaceExample implements GfG,gfg { public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); }}", "e": 26614, "s": 26080, "text": null }, { "code": null, "e": 26622, "s": 26614, "text": "Output:" }, { "code": null, "e": 26849, "s": 26622, "text": "InterfaceExample.java:18: error: types GfG and gfg are incompatible;\npublic class InterfaceExample implements GfG,gfg {\n ^\n class InterfaceExample inherits unrelated defaults for display() from types GfG and gfg\n1 error" }, { "code": null, "e": 26892, "s": 26849, "text": "Case 2: When Two Interfaces are Overridden" }, { "code": null, "e": 26897, "s": 26892, "text": "Java" }, { "code": "// Java program to demonstrate the case// when two interfaces are overridden // Creating Interface Oneinterface GfG{ public default void display() { System.out.println(\"GEEKSFORGEEKS\"); }} // Creating Interface Twointerface gfg{ public default void display() { System.out.println(\"geeksforgeeks\"); }} public class InterfaceExample implements GfG,gfg { // Interfaces are Overridedpublic void display() { GfG.super.display(); gfg.super.display(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); }}", "e": 27515, "s": 26897, "text": null }, { "code": null, "e": 27543, "s": 27515, "text": "GEEKSFORGEEKS\ngeeksforgeeks" }, { "code": null, "e": 27550, "s": 27543, "text": "Java 8" }, { "code": null, "e": 27566, "s": 27550, "text": "java-overriding" }, { "code": null, "e": 27573, "s": 27566, "text": "Picked" }, { "code": null, "e": 27597, "s": 27573, "text": "Technical Scripter 2020" }, { "code": null, "e": 27602, "s": 27597, "text": "Java" }, { "code": null, "e": 27621, "s": 27602, "text": "Technical Scripter" }, { "code": null, "e": 27626, "s": 27621, "text": "Java" }, { "code": null, "e": 27724, "s": 27626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27733, "s": 27724, "text": "Comments" }, { "code": null, "e": 27746, "s": 27733, "text": "Old Comments" }, { "code": null, "e": 27778, "s": 27746, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27808, "s": 27778, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27827, "s": 27808, "text": "Interfaces in Java" }, { "code": null, "e": 27878, "s": 27827, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27896, "s": 27878, "text": "ArrayList in Java" }, { "code": null, "e": 27927, "s": 27896, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27959, "s": 27927, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27978, "s": 27959, "text": "LinkedList in Java" }, { "code": null, "e": 27998, "s": 27978, "text": "Stack Class in Java" } ]
How to change the password in MongoDB for existing user?
To change the password in MongoDB for existing user, you can use changeUserPassword(). Following is the syntax db.changeUserPassword("yourExistingUserName", "yourPassword"); Let us first switch the database to admin. Following is the syntax > use admin This will produce the following output switched to db admin Now, display users from the database. Following is the query > db.getUsers(); This will produce the following output [ { "_id" : "admin.John", "user" : "John", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } ] Following is the query to change the password for user “John” > db.changeUserPassword("John", "123456"); Now the password has been changed with value “123456”.
[ { "code": null, "e": 1173, "s": 1062, "text": "To change the password in MongoDB for existing user, you can use changeUserPassword(). Following is the syntax" }, { "code": null, "e": 1236, "s": 1173, "text": "db.changeUserPassword(\"yourExistingUserName\", \"yourPassword\");" }, { "code": null, "e": 1303, "s": 1236, "text": "Let us first switch the database to admin. Following is the syntax" }, { "code": null, "e": 1315, "s": 1303, "text": "> use admin" }, { "code": null, "e": 1354, "s": 1315, "text": "This will produce the following output" }, { "code": null, "e": 1375, "s": 1354, "text": "switched to db admin" }, { "code": null, "e": 1436, "s": 1375, "text": "Now, display users from the database. Following is the query" }, { "code": null, "e": 1453, "s": 1436, "text": "> db.getUsers();" }, { "code": null, "e": 1492, "s": 1453, "text": "This will produce the following output" }, { "code": null, "e": 1780, "s": 1492, "text": "[\n {\n \"_id\" : \"admin.John\",\n \"user\" : \"John\",\n \"db\" : \"admin\",\n \"roles\" : [\n {\n \"role\" : \"userAdminAnyDatabase\",\n \"db\" : \"admin\"\n }\n ],\n \"mechanisms\" : [\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ]\n }\n]" }, { "code": null, "e": 1842, "s": 1780, "text": "Following is the query to change the password for user “John”" }, { "code": null, "e": 1885, "s": 1842, "text": "> db.changeUserPassword(\"John\", \"123456\");" }, { "code": null, "e": 1940, "s": 1885, "text": "Now the password has been changed with value “123456”." } ]
C program to find the sum of arithmetic progression series
Find the sum of an arithmetic progression series, where the user has to enter first number, total number of elements and the common difference. Arithmetic Progression (A.P.) is a series of numbers in which the difference of any two consecutive numbers is always the same. Here, total number of elements is mentioned as Tn. Sum of A.P. Series: Sn = n/2(2a + (n – 1) d) Tn term of A.P. Series: Tn = a + (n – 1) d Refer an algorithm given below to find the arithmetic progression. Step 1: Declare variables. Step 2: Initialize sum=0 Step 3: Enter first number of series at runtime. Step 4: Enter total number of series at runtime. Step 5: Enter the common difference at runtime. Step 6: Compute sum by using the formula given below. sum = (num * (2 * a + (num - 1) * diff)) / 2 Step 7: Compute tn by using the formula given below. tn = a + (num - 1) * diff Step 8: For loop i = a; i <= tn; i = i + diff i. if(i != tn) printf("%d + ", i); ii. Else, printf("%d = %d", i, sum); Step 9: Print new line Following is the C Program to find the sum of arithmetic progression series− Live Demo #include <stdio.h> int main() { int a, num, diff, tn, i; int sum = 0; printf(" enter 1st no of series: "); scanf("%d", &a); printf(" enter total no's in series: "); scanf("%d", &num); printf("enter Common Difference: "); scanf("%d", &diff); sum = (num * (2 * a + (num - 1) * diff)) / 2; tn = a + (num - 1) * diff; printf("\n sum of A.P series is : "); for(i = a; i <= tn; i = i + diff){ if(i != tn) printf("%d + ", i); else printf("%d = %d", i, sum); } printf("\n"); return 0; } When the above program is executed, it produces the following result − enter 1st no of series: 3 enter total no's in series: 10 enter Common Difference: 5 sum of A.P series is: 3 + 8 + 13 + 18 + 23 + 28 + 33 + 38 + 43 + 48 = 255 enter 1st no of series: 2 enter total no's in series: 15 enter Common Difference: 10 sum of A.P series is: 2 + 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 + 112 + 122 + 132 + 142 = 1080
[ { "code": null, "e": 1206, "s": 1062, "text": "Find the sum of an arithmetic progression series, where the user has to enter first number, total number of elements and the common difference." }, { "code": null, "e": 1385, "s": 1206, "text": "Arithmetic Progression (A.P.) is a series of numbers in which the difference of any two consecutive numbers is always the same. Here, total number of elements is mentioned as Tn." }, { "code": null, "e": 1473, "s": 1385, "text": "Sum of A.P. Series: Sn = n/2(2a + (n – 1) d)\nTn term of A.P. Series: Tn = a + (n – 1) d" }, { "code": null, "e": 1540, "s": 1473, "text": "Refer an algorithm given below to find the arithmetic progression." }, { "code": null, "e": 2084, "s": 1540, "text": "Step 1: Declare variables.\nStep 2: Initialize sum=0\nStep 3: Enter first number of series at runtime.\nStep 4: Enter total number of series at runtime.\nStep 5: Enter the common difference at runtime.\nStep 6: Compute sum by using the formula given below.\n sum = (num * (2 * a + (num - 1) * diff)) / 2\nStep 7: Compute tn by using the formula given below.\n tn = a + (num - 1) * diff\nStep 8: For loop\n i = a; i <= tn; i = i + diff\n i. if(i != tn)\n printf(\"%d + \", i);\n ii. Else,\n printf(\"%d = %d\", i, sum);\nStep 9: Print new line" }, { "code": null, "e": 2161, "s": 2084, "text": "Following is the C Program to find the sum of arithmetic progression series−" }, { "code": null, "e": 2172, "s": 2161, "text": " Live Demo" }, { "code": null, "e": 2726, "s": 2172, "text": "#include <stdio.h>\nint main() {\n int a, num, diff, tn, i;\n int sum = 0;\n printf(\" enter 1st no of series: \");\n scanf(\"%d\", &a);\n printf(\" enter total no's in series: \");\n scanf(\"%d\", &num);\n printf(\"enter Common Difference: \");\n scanf(\"%d\", &diff);\n sum = (num * (2 * a + (num - 1) * diff)) / 2;\n tn = a + (num - 1) * diff;\n printf(\"\\n sum of A.P series is : \");\n for(i = a; i <= tn; i = i + diff){\n if(i != tn)\n printf(\"%d + \", i);\n else\n printf(\"%d = %d\", i, sum);\n }\n printf(\"\\n\");\n return 0;\n}" }, { "code": null, "e": 2797, "s": 2726, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3146, "s": 2797, "text": "enter 1st no of series: 3\nenter total no's in series: 10\nenter Common Difference: 5\nsum of A.P series is: 3 + 8 + 13 + 18 + 23 + 28 + 33 + 38 + 43 + 48 = 255\nenter 1st no of series: 2\nenter total no's in series: 15\nenter Common Difference: 10\nsum of A.P series is: 2 + 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 + 112 + 122 + 132 + 142 = 1080" } ]
B-Tree Insert without aggressive splitting - GeeksforGeeks
25 Jun, 2021 B-Tree Insert without aggressive splittingThis algorithm for insertion takes an entry, finds the leaf node where it belongs, and inserts it there. We recursively insert the entry by calling the insert algorithm on the appropriate child node. This procedure results in going down to the leaf node where the entry belongs, placing the entry there, and returning all the way back to the root node. Sometimes a node is full, i.e. it contains 2*t – 1 entries where t is the minimum degree. In such cases the node must be split. In such case one key becomes a parent and a new node is created. We first insert the new key, making total keys as 2*t. We keep the first t entries in original node, transfer last (t-1) entries to new node and set the (t+1)th node as parent of these nodes. If the node being split is a non child node then we also have to split the child pointers. A node having 2*t keys has 2*t + 1 child pointers. The first (t+1) pointers are kept in original node and remaining t pointers goes to new node. This algorithm splits a node only when it is necessary. We first recursively call insert for appropriate child of node (in case of non-leaf node) or insert it into node (for leaf node). If the node is full, we split it, storing new child entry in newEntry and new parent key in val. These values are then inserted into the parent, which recursively splits itself in case it is also full.Example:We insert numbers 1 – 5 in tree. The tree becomes: Then we insert 6, the node is full. Hence it is split into two nodes making 4 as parent. We insert numbers 7 – 16, the tree becomes: We insert 22 – 30, the tree becomes: Note that now the root is full. If we insert 17 now, the root is not split as the leaf node in which 17 was inserted didn’t split. If we were following aggressive splitting, the root would have been split before we went to leaf node. But if we insert 31, the leaf node splits, which recursively adds new entry to root. But as root is full, it needs to be split. The tree now becomes. Below is the implementation of the above approach: CPP // C++ implementation of the approach#include <iostream>#include <vector>using namespace std; class BTreeNode { // Vector of keys vector<int> keys; // Minimum degree int t; // Vector of child pointers vector<BTreeNode*> C; // Is true when node is leaf, else false bool leaf; public: // Constructor BTreeNode(int t, bool leaf); // Traversing the node and print its content // with tab number of tabs before void traverse(int tab); // Insert key into given node. If child is split, we // have to insert *val entry into keys vector and // newEntry pointer into C vector of this node void insert(int key, int* val, BTreeNode*& newEntry); // Split this node and store the new parent value in // *val and new node pointer in newEntry void split(int* val, BTreeNode*& newEntry); // Returns true if node is full bool isFull(); // Makes new root, setting current root as its child BTreeNode* makeNewRoot(int val, BTreeNode* newEntry);}; bool BTreeNode::isFull(){ // returns true if node is full return (this->keys.size() == 2 * t - 1);} BTreeNode::BTreeNode(int t, bool leaf){ // Constructor to set value of t and leaf this->t = t; this->leaf = leaf;} // Function to print the nodes of B-Treevoid BTreeNode::traverse(int tab){ int i; string s; // Print 'tab' number of tabs for (int j = 0; j < tab; j++) { s += '\t'; } for (i = 0; i < keys.size(); i++) { // If this is not leaf, then before printing key[i] // traverse the subtree rooted with child C[i] if (leaf == false) C[i]->traverse(tab + 1); cout << s << keys[i] << endl; } // Print the subtree rooted with last child if (leaf == false) { C[i]->traverse(tab + 1); }} // Function to split the current node and store the new// parent value is *val and new child pointer in &newEntry// called only for splitting non-leaf nodevoid BTreeNode::split(int* val, BTreeNode*& newEntry){ // Create new non leaf node newEntry = new BTreeNode(t, false); //(t+1)th becomes parent *val = this->keys[t]; // Last (t-1) entries will go to new node for (int i = t + 1; i < 2 * t; i++) { newEntry->keys.push_back(this->keys[i]); } // This node stores first t entries this->keys.resize(t); // Last t entries will go to new node for (int i = t + 1; i <= 2 * t; i++) { newEntry->C.push_back(this->C[i]); } // This node stores first (t+1) entries this->C.resize(t + 1);} // Function to insert a new key in given node.// If child of this node is split, we have to insert *val// into keys vector and newEntry pointer into C vectorvoid BTreeNode::insert(int new_key, int* val, BTreeNode*& newEntry){ // Non leaf node if (leaf == false) { int i = 0; // Find first key greater than new_key while (i < keys.size() && new_key > keys[i]) i++; // We have to insert new_key into left child of // Node with index i C[i]->insert(new_key, val, newEntry); // No split was done if (newEntry == NULL) return; if (keys.size() < 2 * t - 1) { // This node can accommodate a new key // and child pointer entry // Insert *val into key vector keys.insert(keys.begin() + i, *val); // Insert newEntry into C vector C.insert(C.begin() + i + 1, newEntry); // As this node was not split, set newEntry // to NULL newEntry = NULL; } else { // Insert *val and newentry keys.insert(keys.begin() + i, *val); C.insert(C.begin() + i + 1, newEntry); // Current node has 2*t keys, so split it split(val, newEntry); } } else { // Insert new_key in this node vector<int>::iterator it; // Find correct position it = lower_bound(keys.begin(), keys.end(), new_key); // Insert in correct position keys.insert(it, new_key); // If node is full if (keys.size() == 2 * t) { // Create new node newEntry = new BTreeNode(t, true); // Set (t+1)th key as parent *val = this->keys[t]; // Insert last (t-1) keys into new node for (int i = t + 1; i < 2 * t; i++) { newEntry->keys.push_back(this->keys[i]); } // This node stores first t keys this->keys.resize(t); } }} // Function to create a new root// setting current node as its childBTreeNode* BTreeNode::makeNewRoot(int val, BTreeNode* newEntry){ // Create new root BTreeNode* root = new BTreeNode(t, false); // Stores keys value root->keys.push_back(val); // Push child pointers root->C.push_back(this); root->C.push_back(newEntry); return root;} class BTree { // Root of B-Tree BTreeNode* root; // Minimum degree int t; public: // Constructor BTree(int t); // Insert key void insert(int key); // Display the tree void display();}; // Function to create a new BTree with// minimum degree tBTree::BTree(int t){ root = new BTreeNode(t, true);} // Function to insert a node in the B-Treevoid BTree::insert(int key){ BTreeNode* newEntry = NULL; int val = 0; // Insert in B-Tree root->insert(key, &val, newEntry); // If newEntry is not Null then root needs to be // split. Create new root if (newEntry != NULL) { root = root->makeNewRoot(val, newEntry); }} // Prints BTreevoid BTree::display(){ root->traverse(0);} // Driver codeint main(){ // Create B-Tree BTree* tree = new BTree(3); cout << "After inserting 1 and 2" << endl; tree->insert(1); tree->insert(2); tree->display(); cout << "After inserting 5 and 6" << endl; tree->insert(5); tree->insert(6); tree->display(); cout << "After inserting 3 and 4" << endl; tree->insert(3); tree->insert(4); tree->display(); return 0;} After inserting 1 and 2 1 2 After inserting 5 and 6 1 2 5 6 After inserting 3 and 4 1 2 3 4 5 6 adnanirshad158 B-Tree Advanced Data Structure Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Proof that Dominant Set of a Graph is NP-Complete Extendible Hashing (Dynamic approach to DBMS) 2-3 Trees | (Search, Insert and Deletion) Trie | (Delete) Advantages of Trie Data Structure Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 24488, "s": 24460, "text": "\n25 Jun, 2021" }, { "code": null, "e": 25505, "s": 24488, "text": "B-Tree Insert without aggressive splittingThis algorithm for insertion takes an entry, finds the leaf node where it belongs, and inserts it there. We recursively insert the entry by calling the insert algorithm on the appropriate child node. This procedure results in going down to the leaf node where the entry belongs, placing the entry there, and returning all the way back to the root node. Sometimes a node is full, i.e. it contains 2*t – 1 entries where t is the minimum degree. In such cases the node must be split. In such case one key becomes a parent and a new node is created. We first insert the new key, making total keys as 2*t. We keep the first t entries in original node, transfer last (t-1) entries to new node and set the (t+1)th node as parent of these nodes. If the node being split is a non child node then we also have to split the child pointers. A node having 2*t keys has 2*t + 1 child pointers. The first (t+1) pointers are kept in original node and remaining t pointers goes to new node. " }, { "code": null, "e": 25953, "s": 25505, "text": "This algorithm splits a node only when it is necessary. We first recursively call insert for appropriate child of node (in case of non-leaf node) or insert it into node (for leaf node). If the node is full, we split it, storing new child entry in newEntry and new parent key in val. These values are then inserted into the parent, which recursively splits itself in case it is also full.Example:We insert numbers 1 – 5 in tree. The tree becomes: " }, { "code": null, "e": 26044, "s": 25953, "text": "Then we insert 6, the node is full. Hence it is split into two nodes making 4 as parent. " }, { "code": null, "e": 26089, "s": 26044, "text": "We insert numbers 7 – 16, the tree becomes: " }, { "code": null, "e": 26127, "s": 26089, "text": "We insert 22 – 30, the tree becomes: " }, { "code": null, "e": 26362, "s": 26127, "text": "Note that now the root is full. If we insert 17 now, the root is not split as the leaf node in which 17 was inserted didn’t split. If we were following aggressive splitting, the root would have been split before we went to leaf node. " }, { "code": null, "e": 26513, "s": 26362, "text": "But if we insert 31, the leaf node splits, which recursively adds new entry to root. But as root is full, it needs to be split. The tree now becomes. " }, { "code": null, "e": 26567, "s": 26515, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26571, "s": 26567, "text": "CPP" }, { "code": "// C++ implementation of the approach#include <iostream>#include <vector>using namespace std; class BTreeNode { // Vector of keys vector<int> keys; // Minimum degree int t; // Vector of child pointers vector<BTreeNode*> C; // Is true when node is leaf, else false bool leaf; public: // Constructor BTreeNode(int t, bool leaf); // Traversing the node and print its content // with tab number of tabs before void traverse(int tab); // Insert key into given node. If child is split, we // have to insert *val entry into keys vector and // newEntry pointer into C vector of this node void insert(int key, int* val, BTreeNode*& newEntry); // Split this node and store the new parent value in // *val and new node pointer in newEntry void split(int* val, BTreeNode*& newEntry); // Returns true if node is full bool isFull(); // Makes new root, setting current root as its child BTreeNode* makeNewRoot(int val, BTreeNode* newEntry);}; bool BTreeNode::isFull(){ // returns true if node is full return (this->keys.size() == 2 * t - 1);} BTreeNode::BTreeNode(int t, bool leaf){ // Constructor to set value of t and leaf this->t = t; this->leaf = leaf;} // Function to print the nodes of B-Treevoid BTreeNode::traverse(int tab){ int i; string s; // Print 'tab' number of tabs for (int j = 0; j < tab; j++) { s += '\\t'; } for (i = 0; i < keys.size(); i++) { // If this is not leaf, then before printing key[i] // traverse the subtree rooted with child C[i] if (leaf == false) C[i]->traverse(tab + 1); cout << s << keys[i] << endl; } // Print the subtree rooted with last child if (leaf == false) { C[i]->traverse(tab + 1); }} // Function to split the current node and store the new// parent value is *val and new child pointer in &newEntry// called only for splitting non-leaf nodevoid BTreeNode::split(int* val, BTreeNode*& newEntry){ // Create new non leaf node newEntry = new BTreeNode(t, false); //(t+1)th becomes parent *val = this->keys[t]; // Last (t-1) entries will go to new node for (int i = t + 1; i < 2 * t; i++) { newEntry->keys.push_back(this->keys[i]); } // This node stores first t entries this->keys.resize(t); // Last t entries will go to new node for (int i = t + 1; i <= 2 * t; i++) { newEntry->C.push_back(this->C[i]); } // This node stores first (t+1) entries this->C.resize(t + 1);} // Function to insert a new key in given node.// If child of this node is split, we have to insert *val// into keys vector and newEntry pointer into C vectorvoid BTreeNode::insert(int new_key, int* val, BTreeNode*& newEntry){ // Non leaf node if (leaf == false) { int i = 0; // Find first key greater than new_key while (i < keys.size() && new_key > keys[i]) i++; // We have to insert new_key into left child of // Node with index i C[i]->insert(new_key, val, newEntry); // No split was done if (newEntry == NULL) return; if (keys.size() < 2 * t - 1) { // This node can accommodate a new key // and child pointer entry // Insert *val into key vector keys.insert(keys.begin() + i, *val); // Insert newEntry into C vector C.insert(C.begin() + i + 1, newEntry); // As this node was not split, set newEntry // to NULL newEntry = NULL; } else { // Insert *val and newentry keys.insert(keys.begin() + i, *val); C.insert(C.begin() + i + 1, newEntry); // Current node has 2*t keys, so split it split(val, newEntry); } } else { // Insert new_key in this node vector<int>::iterator it; // Find correct position it = lower_bound(keys.begin(), keys.end(), new_key); // Insert in correct position keys.insert(it, new_key); // If node is full if (keys.size() == 2 * t) { // Create new node newEntry = new BTreeNode(t, true); // Set (t+1)th key as parent *val = this->keys[t]; // Insert last (t-1) keys into new node for (int i = t + 1; i < 2 * t; i++) { newEntry->keys.push_back(this->keys[i]); } // This node stores first t keys this->keys.resize(t); } }} // Function to create a new root// setting current node as its childBTreeNode* BTreeNode::makeNewRoot(int val, BTreeNode* newEntry){ // Create new root BTreeNode* root = new BTreeNode(t, false); // Stores keys value root->keys.push_back(val); // Push child pointers root->C.push_back(this); root->C.push_back(newEntry); return root;} class BTree { // Root of B-Tree BTreeNode* root; // Minimum degree int t; public: // Constructor BTree(int t); // Insert key void insert(int key); // Display the tree void display();}; // Function to create a new BTree with// minimum degree tBTree::BTree(int t){ root = new BTreeNode(t, true);} // Function to insert a node in the B-Treevoid BTree::insert(int key){ BTreeNode* newEntry = NULL; int val = 0; // Insert in B-Tree root->insert(key, &val, newEntry); // If newEntry is not Null then root needs to be // split. Create new root if (newEntry != NULL) { root = root->makeNewRoot(val, newEntry); }} // Prints BTreevoid BTree::display(){ root->traverse(0);} // Driver codeint main(){ // Create B-Tree BTree* tree = new BTree(3); cout << \"After inserting 1 and 2\" << endl; tree->insert(1); tree->insert(2); tree->display(); cout << \"After inserting 5 and 6\" << endl; tree->insert(5); tree->insert(6); tree->display(); cout << \"After inserting 3 and 4\" << endl; tree->insert(3); tree->insert(4); tree->display(); return 0;}", "e": 32691, "s": 26571, "text": null }, { "code": null, "e": 32807, "s": 32691, "text": "After inserting 1 and 2\n1\n2\nAfter inserting 5 and 6\n1\n2\n5\n6\nAfter inserting 3 and 4\n 1\n 2\n 3\n4\n 5\n 6" }, { "code": null, "e": 32824, "s": 32809, "text": "adnanirshad158" }, { "code": null, "e": 32831, "s": 32824, "text": "B-Tree" }, { "code": null, "e": 32855, "s": 32831, "text": "Advanced Data Structure" }, { "code": null, "e": 32860, "s": 32855, "text": "Tree" }, { "code": null, "e": 32865, "s": 32860, "text": "Tree" }, { "code": null, "e": 32963, "s": 32865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32972, "s": 32963, "text": "Comments" }, { "code": null, "e": 32985, "s": 32972, "text": "Old Comments" }, { "code": null, "e": 33035, "s": 32985, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 33081, "s": 33035, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 33123, "s": 33081, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 33139, "s": 33123, "text": "Trie | (Delete)" }, { "code": null, "e": 33173, "s": 33139, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 33223, "s": 33173, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 33258, "s": 33223, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 33292, "s": 33258, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 33333, "s": 33292, "text": "Inorder Tree Traversal without Recursion" } ]
C# | Add an object to the end of the Queue - Enqueue Operation - GeeksforGeeks
01 Feb, 2019 Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue. Queue<T>.Enqueue(T) Method is used to add an object to the end of the Queue<T>. Properties: Enqueue adds an element to the end of the Queue. Dequeue removes the oldest element from the start of the Queue. Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array. Queue accepts null as a valid value for reference types and allows duplicate elements. Syntax : void Enqueue(object obj); The Enqueue() method inserts values at the end of the Queue. Example: // C# code to add an object// to the end of the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue<string> myQueue = new Queue<string>(); // Inserting the elements into the Queue myQueue.Enqueue("one"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("two"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("three"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("four"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("five"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("six"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }} Total number of elements in the Queue are : 1 Total number of elements in the Queue are : 2 Total number of elements in the Queue are : 3 Total number of elements in the Queue are : 4 Total number of elements in the Queue are : 5 Total number of elements in the Queue are : 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.enqueue?view=netframework-4.7.2#System_Collections_Generic_Queue_1_Enqueue__0_ CSharp-Generic-Namespace CSharp-Generic-Queue CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates Difference between Ref and Out keywords in C# Destructors in C# Extension Method in C# C# | Constructors Introduction to .NET Framework C# | Abstract Classes C# | Class and Object C# | Data Types C# | Encapsulation
[ { "code": null, "e": 24528, "s": 24500, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24760, "s": 24528, "text": "Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called dequeue." }, { "code": null, "e": 24840, "s": 24760, "text": "Queue<T>.Enqueue(T) Method is used to add an object to the end of the Queue<T>." }, { "code": null, "e": 24852, "s": 24840, "text": "Properties:" }, { "code": null, "e": 24901, "s": 24852, "text": "Enqueue adds an element to the end of the Queue." }, { "code": null, "e": 24965, "s": 24901, "text": "Dequeue removes the oldest element from the start of the Queue." }, { "code": null, "e": 25070, "s": 24965, "text": "Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue." }, { "code": null, "e": 25140, "s": 25070, "text": "The capacity of a Queue is the number of elements the Queue can hold." }, { "code": null, "e": 25262, "s": 25140, "text": "As elements are added to a Queue, the capacity is automatically increased as required by reallocating the internal array." }, { "code": null, "e": 25349, "s": 25262, "text": "Queue accepts null as a valid value for reference types and allows duplicate elements." }, { "code": null, "e": 25358, "s": 25349, "text": "Syntax :" }, { "code": null, "e": 25385, "s": 25358, "text": "void Enqueue(object obj);\n" }, { "code": null, "e": 25446, "s": 25385, "text": "The Enqueue() method inserts values at the end of the Queue." }, { "code": null, "e": 25455, "s": 25446, "text": "Example:" }, { "code": "// C# code to add an object// to the end of the Queueusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Queue of strings Queue<string> myQueue = new Queue<string>(); // Inserting the elements into the Queue myQueue.Enqueue(\"one\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"two\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"three\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"four\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"five\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"six\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}", "e": 27116, "s": 25455, "text": null }, { "code": null, "e": 27393, "s": 27116, "text": "Total number of elements in the Queue are : 1\nTotal number of elements in the Queue are : 2\nTotal number of elements in the Queue are : 3\nTotal number of elements in the Queue are : 4\nTotal number of elements in the Queue are : 5\nTotal number of elements in the Queue are : 6\n" }, { "code": null, "e": 27404, "s": 27393, "text": "Reference:" }, { "code": null, "e": 27562, "s": 27404, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.queue-1.enqueue?view=netframework-4.7.2#System_Collections_Generic_Queue_1_Enqueue__0_" }, { "code": null, "e": 27587, "s": 27562, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27608, "s": 27587, "text": "CSharp-Generic-Queue" }, { "code": null, "e": 27622, "s": 27608, "text": "CSharp-method" }, { "code": null, "e": 27625, "s": 27622, "text": "C#" }, { "code": null, "e": 27723, "s": 27625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27738, "s": 27723, "text": "C# | Delegates" }, { "code": null, "e": 27784, "s": 27738, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27802, "s": 27784, "text": "Destructors in C#" }, { "code": null, "e": 27825, "s": 27802, "text": "Extension Method in C#" }, { "code": null, "e": 27843, "s": 27825, "text": "C# | Constructors" }, { "code": null, "e": 27874, "s": 27843, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27896, "s": 27874, "text": "C# | Abstract Classes" }, { "code": null, "e": 27918, "s": 27896, "text": "C# | Class and Object" }, { "code": null, "e": 27934, "s": 27918, "text": "C# | Data Types" } ]
How to declare an Array Variables in Java?
You can declare an array just like a variable − int myArray[]; You can create an array just like an object using the new keyword − myArray = new int[5]; You can initialize the array by assigning values to all the elements one by one using the index − myArray [0] = 101; myArray [1] = 102; You can access the array element using the index values − System.out.println("The first element of the array is: " + myArray [0]); System.out.println("The first element of the array is: " + myArray [1]); Alternatively, you can create and initialize an array using the flower braces ({ }): Int [] myArray = {10, 20, 30, 40, 50}
[ { "code": null, "e": 1110, "s": 1062, "text": "You can declare an array just like a variable −" }, { "code": null, "e": 1125, "s": 1110, "text": "int myArray[];" }, { "code": null, "e": 1193, "s": 1125, "text": "You can create an array just like an object using the new keyword −" }, { "code": null, "e": 1215, "s": 1193, "text": "myArray = new int[5];" }, { "code": null, "e": 1313, "s": 1215, "text": "You can initialize the array by assigning values to all the elements one by one using the index −" }, { "code": null, "e": 1351, "s": 1313, "text": "myArray [0] = 101;\nmyArray [1] = 102;" }, { "code": null, "e": 1409, "s": 1351, "text": "You can access the array element using the index values −" }, { "code": null, "e": 1678, "s": 1409, "text": "System.out.println(\"The first element of the array is: \" + myArray [0]);\nSystem.out.println(\"The first element of the array is: \" + myArray [1]);\nAlternatively, you can create and initialize an array using the flower braces ({ }):\nInt [] myArray = {10, 20, 30, 40, 50}" } ]
A Beginner’s Guide to Hadoop’s Fundamentals | Towards Data Science
Literally, Hadoop was the name of a toy elephant — specifically, the toy elephant of Doug Cutting’s (Hadoop’s co-founder) son. But you’re not here to learn how, or from where, Hadoop got its name! Broadly speaking, Hadoop is a general-purpose, operating system-like platform for parallel computing. I am sure I do not need to mention the severe limitations of a single system when it comes to processing all the big data floating around us — it is simply beyond the processing capacity of a single machine. Hadoop provides a framework to process this big data through parallel processing, similar to what supercomputers are used for. But why can’t we utilize supercomputers to parallelize the processing of big data: There is no standardized operating system (or an operating system like-framework) for supercomputers — making them less accessible to small and mid-sized organizations High cost of both the initial purchase and regular maintenance Hardware support is tied to a specific vendor, i.e., a company cannot procure the various individual components from different vendors and stack them together In most cases, custom software needs to be developed to operate a supercomputer based on the specific use case Not easy to scale horizontally Hadoop comes to the rescue as it takes care of all the above limitations: it’s an open-source (with strong community support and regular updates), operating system-like platform for parallel processing that does not rely on specific hardware vendors for ongoing hardware support (works with commodity hardware) and does not require any proprietary software. There have been three stable releases of Hadoop since 2006: Hadoop 1, Hadoop 2, and Hadoop 3. Let’s now look at Hadoop’s architecture in more detail — I will start with Hadoop 1, which will make it easier for us to understand Hadoop 2’s architecture later on. I will also assume some basic familiarity with the following terms: commodity hardware, cluster & cluster node, distributed system, and hot standby. Following are the major physical components of the Hadoop 1 architecture: Master Nodes: Name Node: Hadoop’s centralized file system manager, that keeps track of the number of blocks a data file was broken into, the block size, and which data nodes will save and process each file block — without saving any data within itself Secondary Name Node: Backup for the Name Node, but not on hot standby Job Tracker: Hadoop’s centralized job scheduler that is responsible for scheduling the execution of a job on data nodes Each of the above nodes represents an individual machine in a production environment, working in the master mode, that are usually placed in different racks in a production setup (to avoid the failure of one rack bringing down multiple master nodes). Slave Nodes: Data Nodes: Individual machines/systems where the working files, in the form of data blocks, are stored and processed upon Task Tracker: A software service to monitor the state of the Job Tracker, keep track of activities being performed by the Data Node, and report the status to the Job Tracker. One Task Tracker for each Data Node The slave nodes cannot function without the master nodes and are fully dependant on the instructions that they receive from the master nodes before undertaking any kind of processing activities. To ensure continuous uptime, slave nodes send a heartbeat signal to the name node once every three seconds to confirm that they’re up and active. All the above master and slave nodes are interconnected through networking infrastructure to each other to form a cluster. In terms of processing capacities, Job Tracker is more powerful than the Name and Secondary Name Nodes with neither requiring substantial storage capacity. However, the data nodes are the most powerful machines within the cluster with substantial RAM and processing capabilities. Following are the three primary deployment or configuration modes supported by Hadoop: Standalone Mode: All Hadoop services (i.e., each of the Name Node, Secondary Name Node, Job Tracker, and Data Nodes) run locally on a single machine within a single Java Virtual Machine (JVM). However, the standalone mode is seldom used nowadaysPseudo Distributed Mode: All Hadoop services run locally on a single machine but within different JVMs. Pseudo Distributed Mode is usually used during development and testing activities and for educational purposesFully Distributed Mode: Used in a production setup, where all Hadoop services run on separate and dedicated machines/servers Standalone Mode: All Hadoop services (i.e., each of the Name Node, Secondary Name Node, Job Tracker, and Data Nodes) run locally on a single machine within a single Java Virtual Machine (JVM). However, the standalone mode is seldom used nowadays Pseudo Distributed Mode: All Hadoop services run locally on a single machine but within different JVMs. Pseudo Distributed Mode is usually used during development and testing activities and for educational purposes Fully Distributed Mode: Used in a production setup, where all Hadoop services run on separate and dedicated machines/servers A Job in the Hadoop ecosystem is analogous to a Python script/program that one can execute in order to perform a certain task(s). Just like a Python script, Hadoop’s job is a program(s), typically as a JAR file, that is submitted to the Hadoop cluster in order to be processed and executed on the input (raw) data that resides on the data nodes and the post-processed output is saved at a specified location. Now let’s move on from Hadoop’s physical infrastructure to its software components. The core software components of Hadoop are: Hadoop Distributed File System (HDFS) used for data storage and retrievalMapReduce, a parallel processing Java-based framework, is Hadoop’s programming arm that processes the data made available by the HDFS Hadoop Distributed File System (HDFS) used for data storage and retrieval MapReduce, a parallel processing Java-based framework, is Hadoop’s programming arm that processes the data made available by the HDFS MapReduce is further comprised of: A user-defined Map phase, which performs parallel processing of the input data A user-defined Reduce phase, that aggregates the output of the Map phase Just to be clear, Hadoop is a parallel processing platform providing the hardware and software tools to allow parallel processing) that then makes available the MapReduce framework (i.e., a bare-bone skeleton that can be customized based on the user requirements) for parallel processing. But MapReduce is not the only framework supported by Hadoop — Spark is another. HDFS is the file-management component of the Hadoop ecosystem that is responsible for storing and keeping track of large data sets (both structured and unstructured data) across the various data nodes. In order to understand the working of HDFS, let consider an input file of size 200MB. As explained earlier, in order to facilitate parallel processing on data nodes, this single file will be broken down into multiple blocks and saved on the data nodes. The default split size (that is a global setting and can be configured by the Hadoop administrator) in HDFS is 64MB. Therefore, our sample input file of 200MB will be split into 4 blocks — where 3 blocks will be of 64MB and the 4th block will be 8MB. The splitting of the input file into individual blocks and saving them on specific data nodes is taken care of by HDFS. One critical aspect to take note of here is that the splitting of the input file by HDFS happens on the client machine that is outside the Hadoop cluster and the name node decides the placement of each data block into the specific data nodes, based on a specific algorithm. So the client machine directly writes the data blocks to the data nodes once the name node has provided it with the block placement strategy. The name node, acting as the Table of Contents of a book, remembers the placement of each data block within the various name nodes, together with other information, e.g., block size, hostname, etc., in a file table called the File System Image (FS Image). So what happens in case of failure of a data node? The failure of even one data node will result in the entire input file being corrupted — since one piece of our puzzle has gone missing! In a typical production setup, where we are usually dealing with data blocks of hundreds of gigabytes, it is highly inefficient and time-consuming to push the original data file back into the Hadoop cluster. To avoid any potential data loss, backup copies of data blocks on each data node is kept on an adjacent data node. The number of backup copies to be made of each data block is controlled by the Replication Factor. By default, the replication factor is set at 3, i.e., every block of data on each data node is saved on 2 additional backup data nodes so that the Hadoop cluster will have 3 copies of each data block. This replication factor can be configured on a per-file basis at the time of pushing the source data file into HDFS. The backup data node will kick-in as soon as any data node fails to send a heartbeat signal to the name node. Once a backup data node is up and running, the name node will initiate another backup of the data block so that the replication factor of 3 holds throughout the cluster. In Hadoop 1.0, the Secondary Name Node acts as a backup of the Name Node’s FS image. However, and this was one of Hadoop 1.0’s primary limitations, the Secondary Name Node does not operate in a hot standby mode. Therefore, in the event of the Name Node’s failure, the entire Hadoop cluster will go down (data will be present in the Data Nodes, however, it will be inaccessible since the cluster has lost the FS image), and the contents of the Secondary Name Node need to be manually copied to the Name Nome. We will go over this later — but this limation was addressed with the release of Hadoop 2.0, where the Secondary Name Node acts as a Hot Standby. Hadoop 2.0 is also sometimes known as MapReduce 2 (MR2) or Yet Another Resource Negotiator (YARN). Let’s try to understand the salient architectural differences between Hadoop 1.0 and Hadoop 2.0. Remember that, in Hadoop 1.0, the Job Tracker acts as a centralized job scheduler that splits up a specific job into multiple jobs before passing them on to individual data nodes — where the individual tasks on the data nodes are monitored by the Task Tracker that then reports back the status to the Job Tracker. In addition to its job scheduling responsibilities, the Job Tracker also allocates the system resources to each data node in a static mode (that is, the system resources are not dynamic). Hadoop 2.0 replaces the Job Tracker with YARN while the underlying file system remaining as HDFS. In addition to MapReduce, YARN also supports other parallel processing frameworks, e.g., Spark. YARN can also support up to 10,000 data notes, compared to only 4,000 data nodes supported by Hadoop 1.0’s Job Tracker. YARN has 2 components: Scheduler and Applications Manager. Both these tasks were managed single-handedly by the Job Tracker in Hadoop 1.0. Separating these distinct responsibilities into YARN’s individual components allows better utilization of system resources. Further, the task trackers on each data node were replaced by a single Node Manager (that works in the slave mode) in Hadoop 2.0. Node Manager communicates directly with YARN’s Applications Manager for resource management. As alluded to earlier, in addition to a Secondary Name Node, Hadoop 2.0 also has a Hot Standby Name Node that seamlessly kicks-in in case of Name Node’s failure. The Secondary Name Node comes in handy in case of the failure of both the Name and the Hot Standby Name Node. As the name suggests, MapReduce is comprised of the following 2 stages with each stage having 3 further sub-stages: All 3 sub-stages of the Map stage are performed or acted upon in each of the data blocks residing in the individual data nodes — this is where parallelization kicks-in within Hadoop. Record Reader The Record Reader is pre-programmed to process one line at a time from the input file and produces 2 outputs: Key: a number Value: the entire line Mapper Mapper is programmable to process each key-value pair output from the Record Reader one at a time based on any required logic or the problem statement. It outputs additional Key-Value pairs based on a user-defined function it was programmed to perform. Sorter The output from Mapper is fed into the Sorter that lexicographically sorts (obviously! 😊) the keys from the Mapper’s output. In case the keys are numeric, then the Sorter will perform a numerical sorting. The Sorter is pre-programmed and the only configuration possible is to implement sorting on values. At the end of the Map stage, we will have multiple Mapper outputs, one from each of the data nodes. All these outputs will be transferred to a separate, single data node where the Reduce operation will be implemented on them. The 3 sub-stages of the Reduce operation are: Merge Intermediary outputs from each Map operation are appended to one another to result in a single merged file. Shuffler Shuffler is another pre-programmed built-in module that aggregates together the duplicate keys as present in its input, resulting in a list of values for each unique key. Reducer Shuffler’s output is fed to the Reducer, which is the programmable module of the Reduce stage — similar to the Mapper. Reducer produces output in key-value pairs based on what it is programmed to perform as per the problem statement. I will use a very simple, non-ML problem statement to try and explain the mechanics and the workflow of MapReduce. Consider an input file with just 2 statements as follows: Processing big data through Hadoop is easyHadoop is not the only big data processing platform Our task is to find the frequency of words in the input file, the expected output being: Processing 2big 2data 2through 1Hadoop 2is 2easy 1not 1the 1only 1platform 1 Going through the MapReduce stages explained above: the output of Record Reader after reading the first line will be:Key: 0 (file/line offset — the starting position)Value: Processing big data through Hadoop is easy We can program the Mapper to do the following:Step 1: Ignore the input keyStep 2: Extract each word from the line (tokenization)Step 3: Produce the output in key-value pairs where the key is each word of the line and value is the frequency of that word in the input lineAccordingly, Mapper’s output after processing both lines will be something like this: Processing 1big 1data 1through 1Hadoop 1is 1easy 1Hadoop 1is 1not 1the 1only 1big 1data 1processing 1platform 1 The output from the Sorter will be something like this: big 1big 1data 1data 1easy 1Hadoop 1Hadoop 1is 1is 1not 1only 1platform 1processing 1Processing 1the 1through 1 Shuffler’s output will be something like this: big 1, 1data 1, 1easy 1Hadoop 1, 1is 1, 1not 1only 1platform 1processing 1, 1the 1through 1 Reducer can be programmed to do the following:Step 1: Take the key-value pair from Shuffler’s outputStep 2: Add up the list values for each keyStep 3: Output the key-value pairs where the key remains unchanged and the value is the sum of numbers in the list from Shuffler’s outputStep 4: Repeat the above steps for each key-value pair received from the ShufflerAccordingly, Reducer’s output will be: big 2data 2easy 1Hadoop 2is 2not 1only 1platform 1processing 2the 1through 1 Certain industry use case of MapReduce include: searching for keywords in big datasets Google used it for wordcount, Adwords, page rank, indexing data for Google Search, article clustering for Google News (recently Google has moved on from MapReduce) Text algorithms such as grep, text-indexing, reversing indexing Data mining Facebook uses it for data mining, ad optimization, spam detection Analytics by financial services providers Batch, non-interactive analysis Right, so this was a very high-level and non-technical introduction to the world of Hadoop and MapReduce. Obviously, there are several other Hadoop components that I have not even touched upon here, e.g., Hive, Zookeeper, Pig, HBase, Spark, etc. Please feel free to reach out to me if you want to discuss the above content, or that in any of my previous posts, or anything in general related to data analytics, machine learning, and financial risk. Till next time, rock on!
[ { "code": null, "e": 470, "s": 171, "text": "Literally, Hadoop was the name of a toy elephant — specifically, the toy elephant of Doug Cutting’s (Hadoop’s co-founder) son. But you’re not here to learn how, or from where, Hadoop got its name! Broadly speaking, Hadoop is a general-purpose, operating system-like platform for parallel computing." }, { "code": null, "e": 805, "s": 470, "text": "I am sure I do not need to mention the severe limitations of a single system when it comes to processing all the big data floating around us — it is simply beyond the processing capacity of a single machine. Hadoop provides a framework to process this big data through parallel processing, similar to what supercomputers are used for." }, { "code": null, "e": 888, "s": 805, "text": "But why can’t we utilize supercomputers to parallelize the processing of big data:" }, { "code": null, "e": 1056, "s": 888, "text": "There is no standardized operating system (or an operating system like-framework) for supercomputers — making them less accessible to small and mid-sized organizations" }, { "code": null, "e": 1119, "s": 1056, "text": "High cost of both the initial purchase and regular maintenance" }, { "code": null, "e": 1278, "s": 1119, "text": "Hardware support is tied to a specific vendor, i.e., a company cannot procure the various individual components from different vendors and stack them together" }, { "code": null, "e": 1389, "s": 1278, "text": "In most cases, custom software needs to be developed to operate a supercomputer based on the specific use case" }, { "code": null, "e": 1420, "s": 1389, "text": "Not easy to scale horizontally" }, { "code": null, "e": 1778, "s": 1420, "text": "Hadoop comes to the rescue as it takes care of all the above limitations: it’s an open-source (with strong community support and regular updates), operating system-like platform for parallel processing that does not rely on specific hardware vendors for ongoing hardware support (works with commodity hardware) and does not require any proprietary software." }, { "code": null, "e": 1872, "s": 1778, "text": "There have been three stable releases of Hadoop since 2006: Hadoop 1, Hadoop 2, and Hadoop 3." }, { "code": null, "e": 2187, "s": 1872, "text": "Let’s now look at Hadoop’s architecture in more detail — I will start with Hadoop 1, which will make it easier for us to understand Hadoop 2’s architecture later on. I will also assume some basic familiarity with the following terms: commodity hardware, cluster & cluster node, distributed system, and hot standby." }, { "code": null, "e": 2261, "s": 2187, "text": "Following are the major physical components of the Hadoop 1 architecture:" }, { "code": null, "e": 2275, "s": 2261, "text": "Master Nodes:" }, { "code": null, "e": 2513, "s": 2275, "text": "Name Node: Hadoop’s centralized file system manager, that keeps track of the number of blocks a data file was broken into, the block size, and which data nodes will save and process each file block — without saving any data within itself" }, { "code": null, "e": 2583, "s": 2513, "text": "Secondary Name Node: Backup for the Name Node, but not on hot standby" }, { "code": null, "e": 2703, "s": 2583, "text": "Job Tracker: Hadoop’s centralized job scheduler that is responsible for scheduling the execution of a job on data nodes" }, { "code": null, "e": 2954, "s": 2703, "text": "Each of the above nodes represents an individual machine in a production environment, working in the master mode, that are usually placed in different racks in a production setup (to avoid the failure of one rack bringing down multiple master nodes)." }, { "code": null, "e": 2967, "s": 2954, "text": "Slave Nodes:" }, { "code": null, "e": 3090, "s": 2967, "text": "Data Nodes: Individual machines/systems where the working files, in the form of data blocks, are stored and processed upon" }, { "code": null, "e": 3301, "s": 3090, "text": "Task Tracker: A software service to monitor the state of the Job Tracker, keep track of activities being performed by the Data Node, and report the status to the Job Tracker. One Task Tracker for each Data Node" }, { "code": null, "e": 3642, "s": 3301, "text": "The slave nodes cannot function without the master nodes and are fully dependant on the instructions that they receive from the master nodes before undertaking any kind of processing activities. To ensure continuous uptime, slave nodes send a heartbeat signal to the name node once every three seconds to confirm that they’re up and active." }, { "code": null, "e": 3765, "s": 3642, "text": "All the above master and slave nodes are interconnected through networking infrastructure to each other to form a cluster." }, { "code": null, "e": 4045, "s": 3765, "text": "In terms of processing capacities, Job Tracker is more powerful than the Name and Secondary Name Nodes with neither requiring substantial storage capacity. However, the data nodes are the most powerful machines within the cluster with substantial RAM and processing capabilities." }, { "code": null, "e": 4132, "s": 4045, "text": "Following are the three primary deployment or configuration modes supported by Hadoop:" }, { "code": null, "e": 4716, "s": 4132, "text": "Standalone Mode: All Hadoop services (i.e., each of the Name Node, Secondary Name Node, Job Tracker, and Data Nodes) run locally on a single machine within a single Java Virtual Machine (JVM). However, the standalone mode is seldom used nowadaysPseudo Distributed Mode: All Hadoop services run locally on a single machine but within different JVMs. Pseudo Distributed Mode is usually used during development and testing activities and for educational purposesFully Distributed Mode: Used in a production setup, where all Hadoop services run on separate and dedicated machines/servers" }, { "code": null, "e": 4962, "s": 4716, "text": "Standalone Mode: All Hadoop services (i.e., each of the Name Node, Secondary Name Node, Job Tracker, and Data Nodes) run locally on a single machine within a single Java Virtual Machine (JVM). However, the standalone mode is seldom used nowadays" }, { "code": null, "e": 5177, "s": 4962, "text": "Pseudo Distributed Mode: All Hadoop services run locally on a single machine but within different JVMs. Pseudo Distributed Mode is usually used during development and testing activities and for educational purposes" }, { "code": null, "e": 5302, "s": 5177, "text": "Fully Distributed Mode: Used in a production setup, where all Hadoop services run on separate and dedicated machines/servers" }, { "code": null, "e": 5711, "s": 5302, "text": "A Job in the Hadoop ecosystem is analogous to a Python script/program that one can execute in order to perform a certain task(s). Just like a Python script, Hadoop’s job is a program(s), typically as a JAR file, that is submitted to the Hadoop cluster in order to be processed and executed on the input (raw) data that resides on the data nodes and the post-processed output is saved at a specified location." }, { "code": null, "e": 5839, "s": 5711, "text": "Now let’s move on from Hadoop’s physical infrastructure to its software components. The core software components of Hadoop are:" }, { "code": null, "e": 6046, "s": 5839, "text": "Hadoop Distributed File System (HDFS) used for data storage and retrievalMapReduce, a parallel processing Java-based framework, is Hadoop’s programming arm that processes the data made available by the HDFS" }, { "code": null, "e": 6120, "s": 6046, "text": "Hadoop Distributed File System (HDFS) used for data storage and retrieval" }, { "code": null, "e": 6254, "s": 6120, "text": "MapReduce, a parallel processing Java-based framework, is Hadoop’s programming arm that processes the data made available by the HDFS" }, { "code": null, "e": 6289, "s": 6254, "text": "MapReduce is further comprised of:" }, { "code": null, "e": 6368, "s": 6289, "text": "A user-defined Map phase, which performs parallel processing of the input data" }, { "code": null, "e": 6441, "s": 6368, "text": "A user-defined Reduce phase, that aggregates the output of the Map phase" }, { "code": null, "e": 6810, "s": 6441, "text": "Just to be clear, Hadoop is a parallel processing platform providing the hardware and software tools to allow parallel processing) that then makes available the MapReduce framework (i.e., a bare-bone skeleton that can be customized based on the user requirements) for parallel processing. But MapReduce is not the only framework supported by Hadoop — Spark is another." }, { "code": null, "e": 7012, "s": 6810, "text": "HDFS is the file-management component of the Hadoop ecosystem that is responsible for storing and keeping track of large data sets (both structured and unstructured data) across the various data nodes." }, { "code": null, "e": 7265, "s": 7012, "text": "In order to understand the working of HDFS, let consider an input file of size 200MB. As explained earlier, in order to facilitate parallel processing on data nodes, this single file will be broken down into multiple blocks and saved on the data nodes." }, { "code": null, "e": 7636, "s": 7265, "text": "The default split size (that is a global setting and can be configured by the Hadoop administrator) in HDFS is 64MB. Therefore, our sample input file of 200MB will be split into 4 blocks — where 3 blocks will be of 64MB and the 4th block will be 8MB. The splitting of the input file into individual blocks and saving them on specific data nodes is taken care of by HDFS." }, { "code": null, "e": 8052, "s": 7636, "text": "One critical aspect to take note of here is that the splitting of the input file by HDFS happens on the client machine that is outside the Hadoop cluster and the name node decides the placement of each data block into the specific data nodes, based on a specific algorithm. So the client machine directly writes the data blocks to the data nodes once the name node has provided it with the block placement strategy." }, { "code": null, "e": 8308, "s": 8052, "text": "The name node, acting as the Table of Contents of a book, remembers the placement of each data block within the various name nodes, together with other information, e.g., block size, hostname, etc., in a file table called the File System Image (FS Image)." }, { "code": null, "e": 8704, "s": 8308, "text": "So what happens in case of failure of a data node? The failure of even one data node will result in the entire input file being corrupted — since one piece of our puzzle has gone missing! In a typical production setup, where we are usually dealing with data blocks of hundreds of gigabytes, it is highly inefficient and time-consuming to push the original data file back into the Hadoop cluster." }, { "code": null, "e": 9236, "s": 8704, "text": "To avoid any potential data loss, backup copies of data blocks on each data node is kept on an adjacent data node. The number of backup copies to be made of each data block is controlled by the Replication Factor. By default, the replication factor is set at 3, i.e., every block of data on each data node is saved on 2 additional backup data nodes so that the Hadoop cluster will have 3 copies of each data block. This replication factor can be configured on a per-file basis at the time of pushing the source data file into HDFS." }, { "code": null, "e": 9516, "s": 9236, "text": "The backup data node will kick-in as soon as any data node fails to send a heartbeat signal to the name node. Once a backup data node is up and running, the name node will initiate another backup of the data block so that the replication factor of 3 holds throughout the cluster." }, { "code": null, "e": 10024, "s": 9516, "text": "In Hadoop 1.0, the Secondary Name Node acts as a backup of the Name Node’s FS image. However, and this was one of Hadoop 1.0’s primary limitations, the Secondary Name Node does not operate in a hot standby mode. Therefore, in the event of the Name Node’s failure, the entire Hadoop cluster will go down (data will be present in the Data Nodes, however, it will be inaccessible since the cluster has lost the FS image), and the contents of the Secondary Name Node need to be manually copied to the Name Nome." }, { "code": null, "e": 10170, "s": 10024, "text": "We will go over this later — but this limation was addressed with the release of Hadoop 2.0, where the Secondary Name Node acts as a Hot Standby." }, { "code": null, "e": 10269, "s": 10170, "text": "Hadoop 2.0 is also sometimes known as MapReduce 2 (MR2) or Yet Another Resource Negotiator (YARN)." }, { "code": null, "e": 10868, "s": 10269, "text": "Let’s try to understand the salient architectural differences between Hadoop 1.0 and Hadoop 2.0. Remember that, in Hadoop 1.0, the Job Tracker acts as a centralized job scheduler that splits up a specific job into multiple jobs before passing them on to individual data nodes — where the individual tasks on the data nodes are monitored by the Task Tracker that then reports back the status to the Job Tracker. In addition to its job scheduling responsibilities, the Job Tracker also allocates the system resources to each data node in a static mode (that is, the system resources are not dynamic)." }, { "code": null, "e": 11182, "s": 10868, "text": "Hadoop 2.0 replaces the Job Tracker with YARN while the underlying file system remaining as HDFS. In addition to MapReduce, YARN also supports other parallel processing frameworks, e.g., Spark. YARN can also support up to 10,000 data notes, compared to only 4,000 data nodes supported by Hadoop 1.0’s Job Tracker." }, { "code": null, "e": 11445, "s": 11182, "text": "YARN has 2 components: Scheduler and Applications Manager. Both these tasks were managed single-handedly by the Job Tracker in Hadoop 1.0. Separating these distinct responsibilities into YARN’s individual components allows better utilization of system resources." }, { "code": null, "e": 11668, "s": 11445, "text": "Further, the task trackers on each data node were replaced by a single Node Manager (that works in the slave mode) in Hadoop 2.0. Node Manager communicates directly with YARN’s Applications Manager for resource management." }, { "code": null, "e": 11940, "s": 11668, "text": "As alluded to earlier, in addition to a Secondary Name Node, Hadoop 2.0 also has a Hot Standby Name Node that seamlessly kicks-in in case of Name Node’s failure. The Secondary Name Node comes in handy in case of the failure of both the Name and the Hot Standby Name Node." }, { "code": null, "e": 12056, "s": 11940, "text": "As the name suggests, MapReduce is comprised of the following 2 stages with each stage having 3 further sub-stages:" }, { "code": null, "e": 12239, "s": 12056, "text": "All 3 sub-stages of the Map stage are performed or acted upon in each of the data blocks residing in the individual data nodes — this is where parallelization kicks-in within Hadoop." }, { "code": null, "e": 12253, "s": 12239, "text": "Record Reader" }, { "code": null, "e": 12363, "s": 12253, "text": "The Record Reader is pre-programmed to process one line at a time from the input file and produces 2 outputs:" }, { "code": null, "e": 12377, "s": 12363, "text": "Key: a number" }, { "code": null, "e": 12400, "s": 12377, "text": "Value: the entire line" }, { "code": null, "e": 12407, "s": 12400, "text": "Mapper" }, { "code": null, "e": 12660, "s": 12407, "text": "Mapper is programmable to process each key-value pair output from the Record Reader one at a time based on any required logic or the problem statement. It outputs additional Key-Value pairs based on a user-defined function it was programmed to perform." }, { "code": null, "e": 12667, "s": 12660, "text": "Sorter" }, { "code": null, "e": 12972, "s": 12667, "text": "The output from Mapper is fed into the Sorter that lexicographically sorts (obviously! 😊) the keys from the Mapper’s output. In case the keys are numeric, then the Sorter will perform a numerical sorting. The Sorter is pre-programmed and the only configuration possible is to implement sorting on values." }, { "code": null, "e": 13198, "s": 12972, "text": "At the end of the Map stage, we will have multiple Mapper outputs, one from each of the data nodes. All these outputs will be transferred to a separate, single data node where the Reduce operation will be implemented on them." }, { "code": null, "e": 13244, "s": 13198, "text": "The 3 sub-stages of the Reduce operation are:" }, { "code": null, "e": 13250, "s": 13244, "text": "Merge" }, { "code": null, "e": 13358, "s": 13250, "text": "Intermediary outputs from each Map operation are appended to one another to result in a single merged file." }, { "code": null, "e": 13367, "s": 13358, "text": "Shuffler" }, { "code": null, "e": 13538, "s": 13367, "text": "Shuffler is another pre-programmed built-in module that aggregates together the duplicate keys as present in its input, resulting in a list of values for each unique key." }, { "code": null, "e": 13546, "s": 13538, "text": "Reducer" }, { "code": null, "e": 13780, "s": 13546, "text": "Shuffler’s output is fed to the Reducer, which is the programmable module of the Reduce stage — similar to the Mapper. Reducer produces output in key-value pairs based on what it is programmed to perform as per the problem statement." }, { "code": null, "e": 13953, "s": 13780, "text": "I will use a very simple, non-ML problem statement to try and explain the mechanics and the workflow of MapReduce. Consider an input file with just 2 statements as follows:" }, { "code": null, "e": 14047, "s": 13953, "text": "Processing big data through Hadoop is easyHadoop is not the only big data processing platform" }, { "code": null, "e": 14136, "s": 14047, "text": "Our task is to find the frequency of words in the input file, the expected output being:" }, { "code": null, "e": 14302, "s": 14136, "text": "Processing 2big 2data 2through 1Hadoop 2is 2easy 1not 1the 1only 1platform 1" }, { "code": null, "e": 14354, "s": 14302, "text": "Going through the MapReduce stages explained above:" }, { "code": null, "e": 14518, "s": 14354, "text": "the output of Record Reader after reading the first line will be:Key: 0 (file/line offset — the starting position)Value: Processing big data through Hadoop is easy" }, { "code": null, "e": 14874, "s": 14518, "text": "We can program the Mapper to do the following:Step 1: Ignore the input keyStep 2: Extract each word from the line (tokenization)Step 3: Produce the output in key-value pairs where the key is each word of the line and value is the frequency of that word in the input lineAccordingly, Mapper’s output after processing both lines will be something like this:" }, { "code": null, "e": 15131, "s": 14874, "text": "Processing 1big 1data 1through 1Hadoop 1is 1easy 1Hadoop 1is 1not 1the 1only 1big 1data 1processing 1platform 1" }, { "code": null, "e": 15187, "s": 15131, "text": "The output from the Sorter will be something like this:" }, { "code": null, "e": 15444, "s": 15187, "text": "big 1big 1data 1data 1easy 1Hadoop 1Hadoop 1is 1is 1not 1only 1platform 1processing 1Processing 1the 1through 1" }, { "code": null, "e": 15491, "s": 15444, "text": "Shuffler’s output will be something like this:" }, { "code": null, "e": 15683, "s": 15491, "text": "big 1, 1data 1, 1easy 1Hadoop 1, 1is 1, 1not 1only 1platform 1processing 1, 1the 1through 1" }, { "code": null, "e": 16083, "s": 15683, "text": "Reducer can be programmed to do the following:Step 1: Take the key-value pair from Shuffler’s outputStep 2: Add up the list values for each keyStep 3: Output the key-value pairs where the key remains unchanged and the value is the sum of numbers in the list from Shuffler’s outputStep 4: Repeat the above steps for each key-value pair received from the ShufflerAccordingly, Reducer’s output will be:" }, { "code": null, "e": 16260, "s": 16083, "text": "big 2data 2easy 1Hadoop 2is 2not 1only 1platform 1processing 2the 1through 1" }, { "code": null, "e": 16308, "s": 16260, "text": "Certain industry use case of MapReduce include:" }, { "code": null, "e": 16347, "s": 16308, "text": "searching for keywords in big datasets" }, { "code": null, "e": 16511, "s": 16347, "text": "Google used it for wordcount, Adwords, page rank, indexing data for Google Search, article clustering for Google News (recently Google has moved on from MapReduce)" }, { "code": null, "e": 16575, "s": 16511, "text": "Text algorithms such as grep, text-indexing, reversing indexing" }, { "code": null, "e": 16587, "s": 16575, "text": "Data mining" }, { "code": null, "e": 16653, "s": 16587, "text": "Facebook uses it for data mining, ad optimization, spam detection" }, { "code": null, "e": 16695, "s": 16653, "text": "Analytics by financial services providers" }, { "code": null, "e": 16727, "s": 16695, "text": "Batch, non-interactive analysis" }, { "code": null, "e": 16973, "s": 16727, "text": "Right, so this was a very high-level and non-technical introduction to the world of Hadoop and MapReduce. Obviously, there are several other Hadoop components that I have not even touched upon here, e.g., Hive, Zookeeper, Pig, HBase, Spark, etc." }, { "code": null, "e": 17176, "s": 16973, "text": "Please feel free to reach out to me if you want to discuss the above content, or that in any of my previous posts, or anything in general related to data analytics, machine learning, and financial risk." } ]