title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Fine-Tune GPT-2 for Text Generation | by François St-Amant | Towards Data Science
Natural Language Generation (NLG) has made incredible strides in recent years. In early 2019, OpenAI released GPT-2, a huge pretrained model (1.5B parameters) capable of generating text of human-like quality. Generative Pretrained Transformer 2 (GPT-2) is, like the name says, based on the Transformer. It therefore uses the attention mechanism, which means it learns to focus on previous words that are most relevant to the context in order to predict the next word (for more on this, go here). The goal of this article is to show you how you can fine-tune GPT-2 to generate context relevant text, based on the data you provide to it. As an example, I will be generating song lyrics. The idea is to use the already trained model, fine-tune it to our specific data and then, based on what the model observes, generate what should follow in any given song. GPT-2 on it’s own can generate decent quality text. However, if you want it to do even better for a specific context, you need to fine-tune it on your specific data. In my case, since I want to generate song lyrics, I will be using the following Kaggle dataset, which contains a total of 12,500 popular rock songs lyrics, all in English. Let’s begin by importing the necessary librairies and preparing the data. I recommend using Google Colab for this project, as the access to a GPU will make things much faster for you. As can be seen in lines 26 and 34–35, I created a small test set where I removed the last 20 words of every song. This will allow me to compare the generated text with the actual one to see how well the model performs. In order to use GPT-2 on our data, we still need to do a few things. We need to tokenize the data, which is the process of converting a sequence of characters into tokens, i.e. separating a sentence into words. We also need to ensure that every song respects a maximum of 1024 tokens. The SongLyrics class will do just that for us during the training, for every song in our original dataframe. We can now import the pretrained GPT-2 model, as well as the tokenizer. Also, like I mentionned earlier, GPT-2 is HUGE. It is likely that if you try to use it on your computer, you will be getting a bunch of CUDA Out of Memory errors. An alternative that can be used is to accumulate the gradients. The idea is simply that before calling for optimization to perform a step of gradient descent, it will sum the gradients of several operations. Then, it will divide that total by the number of accumulated steps, in order to get an average loss over the training sample. That means much fewer calculations. And now, finally, we can create the training function that will use all our song lyrics to fine-tune GPT-2 so that it can predict quality verses in the future. Feel free to play around with the various hyperparameters (batch size, learning rate, epochs, optimizer). Then, finally, we can train the model. model = train(dataset, model, tokenizer) Using torch.save and torch.load, you could also save your trained model for future use. The time has come to use our brand new fine-tuned model to generate lyrics. With the use of the following two functions, we can generate lyrics for all songs in our test dataset. Remember, I had removed the last 20 words for every song. Our model will now, for a given song, look at the lyrics he has and come up with what should be the end of the songs. The generate function prepares the generation, while text_generation actually does it, for the entire test dataframe. In line 6 is where we specify what should be the maximum length of a generation. I left it at 30 but that is because punctuation counts, and I will later remove the last couple of words, to ensure the generation finishes at the end of a sentence. Two other hyperparameters are worth mentioning: Temperature (line 8). It is used to scale the probabilities of a given word being generated. Therefore, a high temperature forces the model to make more original predictions while a smaller one keeps the model from going off topic. Top p filtering (line 7). The model will sort the word probabilities in descending order. Then, it will sum those probabilities up to p while dropping the other words. This means the model only keeps themost relevant word probabilities, but does not only keep the best one, as more than one word can be appropriate given a sequence. In the following code, I simply clean the generated text, ensure that it finishes at the end of a sentence (not in the middle of it) and store it in a new column, in the test dataset. There are many ways to evaluate the quality of generated text. The most popular metric is called BLEU. The algorithm outputs a score between 0 and 1, depending how similar a generated text is to reality. A score of 1 indicates that every word that was generated is present in the real text. Here is the code to evaluate BLEU score for the generated lyrics. We obtain an average BLEU score of 0.685, which is pretty good. In comparison, the BLEU score for the GPT-2 model without any fine-tuning was of 0.288. However, BLEU has it’s limits. It was originally created for machine translation and only looks at the vocabulary used to determine the quality of a generated text. That is a problem for us. Indeed, it is possible to generate high quality verses that use entirely different words than reality. That is why I will do a subjective evaluation of the performance of the model. To do that, I created a small web interface (using Dash). The code is available on my Github repository. The way the interface works is that you provide the app with some input words. Then, the model will use that to predict what the next couple of verses should be. Here are a few example outcomes. In red is what the GPT-2 model predicted, given the input sequence in black. You see that it has managed to generate verses that make sense and that respect the context of what came prior! Also, it generates sentences of similar length, which is extremely important when it comes to keeping the rythmn of a song. In that regard, punctuation in the input text is absolutely essential when generating lyrics. As the article shows, by fine-tuning GPT-2 to specific data, it is possible to generate context relevant text fairly easily. For lyrics generation, the model can generate lyrics that respect both the context and the desired length of a sentence. Of course, improvements could be made to the model. For instance we could force it to generate verses that rhyme, something often necessary when writing song lyrics. Thanks a lot for reading, I hope I could help! The repository with all the code and models can be found right here: https://github.com/francoisstamant/lyrics-generation-with-GPT2
[ { "code": null, "e": 380, "s": 171, "text": "Natural Language Generation (NLG) has made incredible strides in recent years. In early 2019, OpenAI released GPT-2, a huge pretrained model (1.5B parameters) capable of generating text of human-like quality." }, { "code": null, "e": 667, "s": 380, "text": "Generative Pretrained Transformer 2 (GPT-2) is, like the name says, based on the Transformer. It therefore uses the attention mechanism, which means it learns to focus on previous words that are most relevant to the context in order to predict the next word (for more on this, go here)." }, { "code": null, "e": 807, "s": 667, "text": "The goal of this article is to show you how you can fine-tune GPT-2 to generate context relevant text, based on the data you provide to it." }, { "code": null, "e": 1027, "s": 807, "text": "As an example, I will be generating song lyrics. The idea is to use the already trained model, fine-tune it to our specific data and then, based on what the model observes, generate what should follow in any given song." }, { "code": null, "e": 1365, "s": 1027, "text": "GPT-2 on it’s own can generate decent quality text. However, if you want it to do even better for a specific context, you need to fine-tune it on your specific data. In my case, since I want to generate song lyrics, I will be using the following Kaggle dataset, which contains a total of 12,500 popular rock songs lyrics, all in English." }, { "code": null, "e": 1549, "s": 1365, "text": "Let’s begin by importing the necessary librairies and preparing the data. I recommend using Google Colab for this project, as the access to a GPU will make things much faster for you." }, { "code": null, "e": 1768, "s": 1549, "text": "As can be seen in lines 26 and 34–35, I created a small test set where I removed the last 20 words of every song. This will allow me to compare the generated text with the actual one to see how well the model performs." }, { "code": null, "e": 1979, "s": 1768, "text": "In order to use GPT-2 on our data, we still need to do a few things. We need to tokenize the data, which is the process of converting a sequence of characters into tokens, i.e. separating a sentence into words." }, { "code": null, "e": 2053, "s": 1979, "text": "We also need to ensure that every song respects a maximum of 1024 tokens." }, { "code": null, "e": 2162, "s": 2053, "text": "The SongLyrics class will do just that for us during the training, for every song in our original dataframe." }, { "code": null, "e": 2397, "s": 2162, "text": "We can now import the pretrained GPT-2 model, as well as the tokenizer. Also, like I mentionned earlier, GPT-2 is HUGE. It is likely that if you try to use it on your computer, you will be getting a bunch of CUDA Out of Memory errors." }, { "code": null, "e": 2461, "s": 2397, "text": "An alternative that can be used is to accumulate the gradients." }, { "code": null, "e": 2767, "s": 2461, "text": "The idea is simply that before calling for optimization to perform a step of gradient descent, it will sum the gradients of several operations. Then, it will divide that total by the number of accumulated steps, in order to get an average loss over the training sample. That means much fewer calculations." }, { "code": null, "e": 2927, "s": 2767, "text": "And now, finally, we can create the training function that will use all our song lyrics to fine-tune GPT-2 so that it can predict quality verses in the future." }, { "code": null, "e": 3033, "s": 2927, "text": "Feel free to play around with the various hyperparameters (batch size, learning rate, epochs, optimizer)." }, { "code": null, "e": 3072, "s": 3033, "text": "Then, finally, we can train the model." }, { "code": null, "e": 3113, "s": 3072, "text": "model = train(dataset, model, tokenizer)" }, { "code": null, "e": 3201, "s": 3113, "text": "Using torch.save and torch.load, you could also save your trained model for future use." }, { "code": null, "e": 3556, "s": 3201, "text": "The time has come to use our brand new fine-tuned model to generate lyrics. With the use of the following two functions, we can generate lyrics for all songs in our test dataset. Remember, I had removed the last 20 words for every song. Our model will now, for a given song, look at the lyrics he has and come up with what should be the end of the songs." }, { "code": null, "e": 3674, "s": 3556, "text": "The generate function prepares the generation, while text_generation actually does it, for the entire test dataframe." }, { "code": null, "e": 3921, "s": 3674, "text": "In line 6 is where we specify what should be the maximum length of a generation. I left it at 30 but that is because punctuation counts, and I will later remove the last couple of words, to ensure the generation finishes at the end of a sentence." }, { "code": null, "e": 3969, "s": 3921, "text": "Two other hyperparameters are worth mentioning:" }, { "code": null, "e": 4201, "s": 3969, "text": "Temperature (line 8). It is used to scale the probabilities of a given word being generated. Therefore, a high temperature forces the model to make more original predictions while a smaller one keeps the model from going off topic." }, { "code": null, "e": 4534, "s": 4201, "text": "Top p filtering (line 7). The model will sort the word probabilities in descending order. Then, it will sum those probabilities up to p while dropping the other words. This means the model only keeps themost relevant word probabilities, but does not only keep the best one, as more than one word can be appropriate given a sequence." }, { "code": null, "e": 4718, "s": 4534, "text": "In the following code, I simply clean the generated text, ensure that it finishes at the end of a sentence (not in the middle of it) and store it in a new column, in the test dataset." }, { "code": null, "e": 5009, "s": 4718, "text": "There are many ways to evaluate the quality of generated text. The most popular metric is called BLEU. The algorithm outputs a score between 0 and 1, depending how similar a generated text is to reality. A score of 1 indicates that every word that was generated is present in the real text." }, { "code": null, "e": 5075, "s": 5009, "text": "Here is the code to evaluate BLEU score for the generated lyrics." }, { "code": null, "e": 5227, "s": 5075, "text": "We obtain an average BLEU score of 0.685, which is pretty good. In comparison, the BLEU score for the GPT-2 model without any fine-tuning was of 0.288." }, { "code": null, "e": 5521, "s": 5227, "text": "However, BLEU has it’s limits. It was originally created for machine translation and only looks at the vocabulary used to determine the quality of a generated text. That is a problem for us. Indeed, it is possible to generate high quality verses that use entirely different words than reality." }, { "code": null, "e": 5705, "s": 5521, "text": "That is why I will do a subjective evaluation of the performance of the model. To do that, I created a small web interface (using Dash). The code is available on my Github repository." }, { "code": null, "e": 5900, "s": 5705, "text": "The way the interface works is that you provide the app with some input words. Then, the model will use that to predict what the next couple of verses should be. Here are a few example outcomes." }, { "code": null, "e": 6307, "s": 5900, "text": "In red is what the GPT-2 model predicted, given the input sequence in black. You see that it has managed to generate verses that make sense and that respect the context of what came prior! Also, it generates sentences of similar length, which is extremely important when it comes to keeping the rythmn of a song. In that regard, punctuation in the input text is absolutely essential when generating lyrics." }, { "code": null, "e": 6432, "s": 6307, "text": "As the article shows, by fine-tuning GPT-2 to specific data, it is possible to generate context relevant text fairly easily." }, { "code": null, "e": 6719, "s": 6432, "text": "For lyrics generation, the model can generate lyrics that respect both the context and the desired length of a sentence. Of course, improvements could be made to the model. For instance we could force it to generate verses that rhyme, something often necessary when writing song lyrics." }, { "code": null, "e": 6766, "s": 6719, "text": "Thanks a lot for reading, I hope I could help!" } ]
Python - Ways to convert string to json object
Data send and get generally in a string of dictionary(JSON objects) forms in many web API’s to use that data to extract meaningful information we need to convert that data in dictionary form and use for further operations. Live Demo # converting string to json # using json.loads import json # inititialising json object ini_string = {'vishesh': 1, 'ram' : 5, 'prashant' : 10, 'vishal' : 15} # printing initial json ini_string = json.dumps(ini_string) print ("initial 1st dictionary", ini_string) print ("type of ini_object", type(ini_string)) # converting string to json final_dictionary = json.loads(ini_string) # printing final result print ("final dictionary", str(final_dictionary)) print ("type of final_dictionary", type(final_dictionary)) ('initial 1st dictionary', '{"vishal": 15, "ram": 5, "vishesh": 1, "prashant": 10}') ('type of ini_object', <type 'str'>) ('final dictionary', "{u'vishal': 15, u'ram': 5, u'vishesh': 1, u'prashant': 10}") ('type of final_dictionary', <type 'dict'>)
[ { "code": null, "e": 1285, "s": 1062, "text": "Data send and get generally in a string of dictionary(JSON objects) forms in many web API’s to use that data to extract meaningful information we need to convert that data in dictionary form and use for further operations." }, { "code": null, "e": 1296, "s": 1285, "text": " Live Demo" }, { "code": null, "e": 1810, "s": 1296, "text": "# converting string to json\n# using json.loads\nimport json\n# inititialising json object\nini_string = {'vishesh': 1, 'ram' : 5, 'prashant' : 10, 'vishal' : 15}\n# printing initial json\nini_string = json.dumps(ini_string)\nprint (\"initial 1st dictionary\", ini_string)\nprint (\"type of ini_object\", type(ini_string))\n# converting string to json\nfinal_dictionary = json.loads(ini_string)\n# printing final result\nprint (\"final dictionary\", str(final_dictionary))\nprint (\"type of final_dictionary\", type(final_dictionary))" }, { "code": null, "e": 2059, "s": 1810, "text": "('initial 1st dictionary', '{\"vishal\": 15, \"ram\": 5, \"vishesh\": 1, \"prashant\": 10}')\n('type of ini_object', <type 'str'>)\n('final dictionary', \"{u'vishal': 15, u'ram': 5, u'vishesh': 1, u'prashant': 10}\")\n('type of final_dictionary', <type 'dict'>)" } ]
Multi-Class Text Classification with LSTM | by Susan Li | Towards Data Science
Automatic text classification or document classification can be done in many different ways in machine learning as we have seen before. This article aims to provide an example of how a Recurrent Neural Network (RNN) using the Long Short Term Memory (LSTM) architecture can be implemented using Keras. We will use the same data source as we did Multi-Class Text Classification with Scikit-Lean, the Consumer Complaints data set that originated from data.gov. We will use a smaller data set, you can also find the data on Kaggle. In the task, given a consumer complaint narrative, the model attempts to predict which product the complaint is about. This is a multi-class text classification problem. Let’s roll! df = pd.read_csv('consumer_complaints_small.csv')df.info() df.Product.value_counts() After first glance of the labels, we realized that there are things we can do to make our lives easier. Consolidate “Credit reporting” into “Credit reporting, credit repair services, or other personal consumer reports”. Consolidate “Credit card” into “Credit card or prepaid card”. Consolidate “Payday loan” into “Payday loan, title loan, or personal loan”. Consolidate “Virtual currency” into “Money transfer, virtual currency, or money service”. “Other financial service” has very few number of complaints and it does not mean anything, so, I decide to remove it. df.loc[df['Product'] == 'Credit reporting', 'Product'] = 'Credit reporting, credit repair services, or other personal consumer reports'df.loc[df['Product'] == 'Credit card', 'Product'] = 'Credit card or prepaid card'df.loc[df['Product'] == 'Payday loan', 'Product'] = 'Payday loan, title loan, or personal loan'df.loc[df['Product'] == 'Virtual currency', 'Product'] = 'Money transfer, virtual currency, or money service'df = df[df.Product != 'Other financial service'] After consolidation, we have 13 labels: df['Product'].value_counts().sort_values(ascending=False).iplot(kind='bar', yTitle='Number of Complaints', title='Number complaints in each product') Let’s have a look how dirty the texts are: def print_plot(index): example = df[df.index == index][['Consumer complaint narrative', 'Product']].values[0] if len(example) > 0: print(example[0]) print('Product:', example[1])print_plot(10) print_plot(100) Pretty dirty, huh! Our text preprocessing will include the following steps: Convert all text to lower case. Replace REPLACE_BY_SPACE_RE symbols by space in text. Remove symbols that are in BAD_SYMBOLS_RE from text. Remove “x” in text. Remove stop words. Remove digits in text. Now go back to check the quality of our text pre-processing: print_plot(10) print_plot(100) Nice! We are done text pre-processing. Vectorize consumer complaints text, by turning each text into either a sequence of integers or into a vector. Limit the data set to the top 5,0000 words. Set the max number of words in each complaint at 250. # The maximum number of words to be used. (most frequent)MAX_NB_WORDS = 50000# Max number of words in each complaint.MAX_SEQUENCE_LENGTH = 250# This is fixed.EMBEDDING_DIM = 100tokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!"#$%&()*+,-./:;<=>?@[\]^_`{|}~', lower=True)tokenizer.fit_on_texts(df['Consumer complaint narrative'].values)word_index = tokenizer.word_indexprint('Found %s unique tokens.' % len(word_index)) Truncate and pad the input sequences so that they are all in the same length for modeling. X = tokenizer.texts_to_sequences(df['Consumer complaint narrative'].values)X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)print('Shape of data tensor:', X.shape) Converting categorical labels to numbers. Y = pd.get_dummies(df['Product']).valuesprint('Shape of label tensor:', Y.shape) Train test split. X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.10, random_state = 42)print(X_train.shape,Y_train.shape)print(X_test.shape,Y_test.shape) The first layer is the embedded layer that uses 100 length vectors to represent each word. SpatialDropout1D performs variational dropout in NLP models. The next layer is the LSTM layer with 100 memory units. The output layer must create 13 output values, one for each class. Activation function is softmax for multi-class classification. Because it is a multi-class classification problem, categorical_crossentropy is used as the loss function. accr = model.evaluate(X_test,Y_test)print('Test set\n Loss: {:0.3f}\n Accuracy: {:0.3f}'.format(accr[0],accr[1])) plt.title('Loss')plt.plot(history.history['loss'], label='train')plt.plot(history.history['val_loss'], label='test')plt.legend()plt.show(); plt.title('Accuracy')plt.plot(history.history['acc'], label='train')plt.plot(history.history['val_acc'], label='test')plt.legend()plt.show(); The plots suggest that the model has a little over fitting problem, more data may help, but more epochs will not help using the current data. Jupyter notebook can be found on Github. Enjoy the rest of the week!
[ { "code": null, "e": 307, "s": 171, "text": "Automatic text classification or document classification can be done in many different ways in machine learning as we have seen before." }, { "code": null, "e": 629, "s": 307, "text": "This article aims to provide an example of how a Recurrent Neural Network (RNN) using the Long Short Term Memory (LSTM) architecture can be implemented using Keras. We will use the same data source as we did Multi-Class Text Classification with Scikit-Lean, the Consumer Complaints data set that originated from data.gov." }, { "code": null, "e": 881, "s": 629, "text": "We will use a smaller data set, you can also find the data on Kaggle. In the task, given a consumer complaint narrative, the model attempts to predict which product the complaint is about. This is a multi-class text classification problem. Let’s roll!" }, { "code": null, "e": 940, "s": 881, "text": "df = pd.read_csv('consumer_complaints_small.csv')df.info()" }, { "code": null, "e": 966, "s": 940, "text": "df.Product.value_counts()" }, { "code": null, "e": 1070, "s": 966, "text": "After first glance of the labels, we realized that there are things we can do to make our lives easier." }, { "code": null, "e": 1186, "s": 1070, "text": "Consolidate “Credit reporting” into “Credit reporting, credit repair services, or other personal consumer reports”." }, { "code": null, "e": 1248, "s": 1186, "text": "Consolidate “Credit card” into “Credit card or prepaid card”." }, { "code": null, "e": 1324, "s": 1248, "text": "Consolidate “Payday loan” into “Payday loan, title loan, or personal loan”." }, { "code": null, "e": 1414, "s": 1324, "text": "Consolidate “Virtual currency” into “Money transfer, virtual currency, or money service”." }, { "code": null, "e": 1532, "s": 1414, "text": "“Other financial service” has very few number of complaints and it does not mean anything, so, I decide to remove it." }, { "code": null, "e": 2001, "s": 1532, "text": "df.loc[df['Product'] == 'Credit reporting', 'Product'] = 'Credit reporting, credit repair services, or other personal consumer reports'df.loc[df['Product'] == 'Credit card', 'Product'] = 'Credit card or prepaid card'df.loc[df['Product'] == 'Payday loan', 'Product'] = 'Payday loan, title loan, or personal loan'df.loc[df['Product'] == 'Virtual currency', 'Product'] = 'Money transfer, virtual currency, or money service'df = df[df.Product != 'Other financial service']" }, { "code": null, "e": 2041, "s": 2001, "text": "After consolidation, we have 13 labels:" }, { "code": null, "e": 2255, "s": 2041, "text": "df['Product'].value_counts().sort_values(ascending=False).iplot(kind='bar', yTitle='Number of Complaints', title='Number complaints in each product')" }, { "code": null, "e": 2298, "s": 2255, "text": "Let’s have a look how dirty the texts are:" }, { "code": null, "e": 2511, "s": 2298, "text": "def print_plot(index): example = df[df.index == index][['Consumer complaint narrative', 'Product']].values[0] if len(example) > 0: print(example[0]) print('Product:', example[1])print_plot(10)" }, { "code": null, "e": 2527, "s": 2511, "text": "print_plot(100)" }, { "code": null, "e": 2546, "s": 2527, "text": "Pretty dirty, huh!" }, { "code": null, "e": 2603, "s": 2546, "text": "Our text preprocessing will include the following steps:" }, { "code": null, "e": 2635, "s": 2603, "text": "Convert all text to lower case." }, { "code": null, "e": 2689, "s": 2635, "text": "Replace REPLACE_BY_SPACE_RE symbols by space in text." }, { "code": null, "e": 2742, "s": 2689, "text": "Remove symbols that are in BAD_SYMBOLS_RE from text." }, { "code": null, "e": 2762, "s": 2742, "text": "Remove “x” in text." }, { "code": null, "e": 2781, "s": 2762, "text": "Remove stop words." }, { "code": null, "e": 2804, "s": 2781, "text": "Remove digits in text." }, { "code": null, "e": 2865, "s": 2804, "text": "Now go back to check the quality of our text pre-processing:" }, { "code": null, "e": 2880, "s": 2865, "text": "print_plot(10)" }, { "code": null, "e": 2896, "s": 2880, "text": "print_plot(100)" }, { "code": null, "e": 2935, "s": 2896, "text": "Nice! We are done text pre-processing." }, { "code": null, "e": 3045, "s": 2935, "text": "Vectorize consumer complaints text, by turning each text into either a sequence of integers or into a vector." }, { "code": null, "e": 3089, "s": 3045, "text": "Limit the data set to the top 5,0000 words." }, { "code": null, "e": 3143, "s": 3089, "text": "Set the max number of words in each complaint at 250." }, { "code": null, "e": 3569, "s": 3143, "text": "# The maximum number of words to be used. (most frequent)MAX_NB_WORDS = 50000# Max number of words in each complaint.MAX_SEQUENCE_LENGTH = 250# This is fixed.EMBEDDING_DIM = 100tokenizer = Tokenizer(num_words=MAX_NB_WORDS, filters='!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~', lower=True)tokenizer.fit_on_texts(df['Consumer complaint narrative'].values)word_index = tokenizer.word_indexprint('Found %s unique tokens.' % len(word_index))" }, { "code": null, "e": 3660, "s": 3569, "text": "Truncate and pad the input sequences so that they are all in the same length for modeling." }, { "code": null, "e": 3823, "s": 3660, "text": "X = tokenizer.texts_to_sequences(df['Consumer complaint narrative'].values)X = pad_sequences(X, maxlen=MAX_SEQUENCE_LENGTH)print('Shape of data tensor:', X.shape)" }, { "code": null, "e": 3865, "s": 3823, "text": "Converting categorical labels to numbers." }, { "code": null, "e": 3946, "s": 3865, "text": "Y = pd.get_dummies(df['Product']).valuesprint('Shape of label tensor:', Y.shape)" }, { "code": null, "e": 3964, "s": 3946, "text": "Train test split." }, { "code": null, "e": 4124, "s": 3964, "text": "X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.10, random_state = 42)print(X_train.shape,Y_train.shape)print(X_test.shape,Y_test.shape)" }, { "code": null, "e": 4215, "s": 4124, "text": "The first layer is the embedded layer that uses 100 length vectors to represent each word." }, { "code": null, "e": 4276, "s": 4215, "text": "SpatialDropout1D performs variational dropout in NLP models." }, { "code": null, "e": 4332, "s": 4276, "text": "The next layer is the LSTM layer with 100 memory units." }, { "code": null, "e": 4399, "s": 4332, "text": "The output layer must create 13 output values, one for each class." }, { "code": null, "e": 4462, "s": 4399, "text": "Activation function is softmax for multi-class classification." }, { "code": null, "e": 4569, "s": 4462, "text": "Because it is a multi-class classification problem, categorical_crossentropy is used as the loss function." }, { "code": null, "e": 4685, "s": 4569, "text": "accr = model.evaluate(X_test,Y_test)print('Test set\\n Loss: {:0.3f}\\n Accuracy: {:0.3f}'.format(accr[0],accr[1]))" }, { "code": null, "e": 4825, "s": 4685, "text": "plt.title('Loss')plt.plot(history.history['loss'], label='train')plt.plot(history.history['val_loss'], label='test')plt.legend()plt.show();" }, { "code": null, "e": 4967, "s": 4825, "text": "plt.title('Accuracy')plt.plot(history.history['acc'], label='train')plt.plot(history.history['val_acc'], label='test')plt.legend()plt.show();" }, { "code": null, "e": 5109, "s": 4967, "text": "The plots suggest that the model has a little over fitting problem, more data may help, but more epochs will not help using the current data." } ]
How to remove an empty string from a list of empty strings in C#?
Firstly, set a list with empty string as elements. List<string> myList = new List<string>() { " ", " ", " " }; Now let us remove one empty element using index. myList.RemoveAt(0); Live Demo using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> myList = new List<string>() { " ", " ", " " }; Console.Write("Initial list with empty strings...\n"); foreach (string list in myList) { Console.WriteLine(list); } Console.Write("Removing an empty element from the list...\n"); myList.RemoveAt(0); foreach (string list in myList) { Console.WriteLine(list); } Console.WriteLine("Empty List after deleting an empty element is shown above..."); } } Initial list with empty strings... Removing an empty element from the list... Empty List after deleting an empty element is shown above...
[ { "code": null, "e": 1113, "s": 1062, "text": "Firstly, set a list with empty string as elements." }, { "code": null, "e": 1182, "s": 1113, "text": "List<string> myList = new List<string>() {\n \" \",\n \" \",\n \" \"\n};" }, { "code": null, "e": 1231, "s": 1182, "text": "Now let us remove one empty element using index." }, { "code": null, "e": 1251, "s": 1231, "text": "myList.RemoveAt(0);" }, { "code": null, "e": 1262, "s": 1251, "text": " Live Demo" }, { "code": null, "e": 1888, "s": 1262, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n List<string> myList = new List<string>() {\n \" \",\n \" \",\n \" \"\n };\n\n Console.Write(\"Initial list with empty strings...\\n\");\n foreach (string list in myList) {\n Console.WriteLine(list);\n }\n\n Console.Write(\"Removing an empty element from the list...\\n\");\n myList.RemoveAt(0);\n\n foreach (string list in myList) {\n Console.WriteLine(list);\n }\n Console.WriteLine(\"Empty List after deleting an empty element is shown above...\");\n }\n}" }, { "code": null, "e": 2029, "s": 1888, "text": "Initial list with empty strings...\n\nRemoving an empty element from the list...\n\nEmpty List after deleting an empty element is shown above..." } ]
Practical SQL: Create and Query a Relational Database | by Soner Yıldırım | Towards Data Science
SQL is a programming language that is used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables). A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns. In the previous post, we designed and created a sales database that contains 4 relational tables. The following figure displays the structure of the database and tables. We have created the tables but left them empty. In this post, we will populate these tables with appropriate data and then run queries to retrieve data from them. Let’s first take a look at the tables. I’m using the terminal to connect to the sales database I created. $ sudo mysql -u rootmysql> use sales; #connecting to the sales databasemysql> show tables;+-----------------+| Tables_in_sales |+-----------------+| customer || item || purchase || store |+-----------------+ We have 4 tables but all of them are empty. As I have also mentioned in the previous post, some columns are marked as primary keys or foreign keys. Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe. Foreign key is what relates a table to another one. Foreign key contains the primary key of another table. For instance, the “item_id” in the purchase table is a foreign key. It stores the rows from the primary key in the item table. Since the tables contain foreign keys, we need to be careful when inserting data. For instance, if we first insert values to the customer table, we need to set the store_id column as NULL because it refers to the primary key of the store table. After creating store_id values in the store table, we can update the values in the customer table. It will become clear with the following example. We first insert a row in the customer table. mysql> INSERT INTO customer VALUES(1, "John", "Doe", "M", NULL);mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | NULL |+---------+--------+--------+--------+----------+ The value in the store_id column is NULL. We can update it after creating the store_id primary key in the store table. mysql> INSERT INTO store VALUES( -> 1, "1234 Delaware Avenue", "Ashley");mysql> INSERT INTO store VALUES(2, "1234 West Street", "Max");mysql> INSERT INTO store VALUES(3, "1234 Kirkwood Street", "Emily"); This retail business owns 3 stores. Here is the store table. mysql> select * from store;+----------+----------------------+---------+| store_id | address | manager |+----------+----------------------+---------+| 1 | 1234 Delaware Avenue | Ashley || 2 | 1234 West Street | Max || 3 | 1234 Kirkwood Street | Emily |+----------+----------------------+---------+ We can now update the customer table and change the store_id in the first row. mysql> UPDATE customer SET store_id=1 WHERE cust_id=1;mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | 1 |+---------+--------+--------+--------+----------+ Please note that we could have inserted data into the store table first and then into the customer table. In this way, we would not need to go back and update NULL values. I wanted to also show this way for practicing. Let’s add a few more customers in the customer table. mysql> INSERT INTO customer VALUES(2, "Jane", "Doe", "F", 1);mysql> INSERT INTO customer VALUES(3, "Elaine", "Smith", "F", 2);mysql> INSERT INTO customer VALUES(4, "Adam", "Gelvin", "M", 3);mysql> INSERT INTO customer VALUES(5, "Robert", "Sam", "M", 1);mysql> INSERT INTO customer VALUES(6, "Betty", "J.", "F", 2);mysql> INSERT INTO customer VALUES(7, "Alisha", "T.", "F", 3); Here is the current version of the customer table. mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | 1 || 2 | Jane | Doe | F | 1 || 3 | Elaine | Smith | F | 2 || 4 | Adam | Gelvin | M | 3 || 5 | Robert | Sam | M | 1 || 6 | Betty | J. | F | 2 || 7 | Alisha | T. | F | 3 |+---------+--------+--------+--------+----------+ I have populated the item and purchase tables similarly. You can come up with your own made-up values. Here is the item table. mysql> select * from item;+---------+----------------+-------+----------+| item_id | description | price | store_id |+---------+----------------+-------+----------+| 1 | apple | 2.45 | 1 || 2 | banana | 3.45 | 1 || 3 | cereal | 4.20 | 2 || 4 | milk 1 liter | 3.80 | 2 || 5 | cheddar cheese | 4.50 | 2 || 6 | icecream | 6.10 | 2 || 7 | water 2 liters | 1.10 | 3 || 8 | tomato | 0.95 | 1 || 9 | egg 15 | 4.40 | 3 || 10 | sprite 1 liter | 1.60 | 3 |+---------+----------------+-------+----------+ Finally, the purchase table is as below. The tables in the sales database contain some data now. We can retrieve all or some of the data stored in these tables. The SELECT statement of SQL is quite flexible so we can create simple or advanced queries easily. In the following examples, we will write SELECT statements to retrieve the desired data. We will select the cust_id column and set a condition on date column using the WHERE keyword. mysql> SELECT cust_id FROM purchase -> WHERE date = "2020-05-10";+---------+| cust_id |+---------+| 2 || 1 || 4 || 7 || 3 || 3 || 1 || 5 |+---------+ As you can see in the output, some IDs are repeated. We can use the DISTINCT keyword to only display unique elements. mysql> SELECT DISTINCT cust_id FROM purchase -> WHERE date = "2020-05-10";+---------+| cust_id |+---------+| 1 || 2 || 3 || 4 || 5 || 7 |+---------+ We will select the store_id and apply the count function. We also need to group the count by store_id. mysql> SELECT store_id, COUNT(store_id) FROM purchase -> GROUP BY store_id;+----------+-----------------+| store_id | COUNT(store_id) |+----------+-----------------+| 1 | 6 || 2 | 3 || 3 | 1 |+----------+-----------------+ We will select the price from the item table and apply the max function. mysql> SELECT MAX(price) FROM item;+------------+| MAX(price) |+------------+| 6.10 |+------------+ In the previous article, we designed and created the schema of a relational database. In this article, we have populated the tables using the INSERT statement. After, we have run some queries with SELECT statements to retrieve data. In the next article, I will write about creating more advanced queries. We will see the UNION and JOIN operators. We will also cover how to edit tables in terms of adding and removing columns and also deleting rows. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 323, "s": 172, "text": "SQL is a programming language that is used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables)." }, { "code": null, "e": 470, "s": 323, "text": "A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns." }, { "code": null, "e": 640, "s": 470, "text": "In the previous post, we designed and created a sales database that contains 4 relational tables. The following figure displays the structure of the database and tables." }, { "code": null, "e": 803, "s": 640, "text": "We have created the tables but left them empty. In this post, we will populate these tables with appropriate data and then run queries to retrieve data from them." }, { "code": null, "e": 909, "s": 803, "text": "Let’s first take a look at the tables. I’m using the terminal to connect to the sales database I created." }, { "code": null, "e": 1152, "s": 909, "text": "$ sudo mysql -u rootmysql> use sales; #connecting to the sales databasemysql> show tables;+-----------------+| Tables_in_sales |+-----------------+| customer || item || purchase || store |+-----------------+" }, { "code": null, "e": 1300, "s": 1152, "text": "We have 4 tables but all of them are empty. As I have also mentioned in the previous post, some columns are marked as primary keys or foreign keys." }, { "code": null, "e": 1405, "s": 1300, "text": "Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe." }, { "code": null, "e": 1639, "s": 1405, "text": "Foreign key is what relates a table to another one. Foreign key contains the primary key of another table. For instance, the “item_id” in the purchase table is a foreign key. It stores the rows from the primary key in the item table." }, { "code": null, "e": 1983, "s": 1639, "text": "Since the tables contain foreign keys, we need to be careful when inserting data. For instance, if we first insert values to the customer table, we need to set the store_id column as NULL because it refers to the primary key of the store table. After creating store_id values in the store table, we can update the values in the customer table." }, { "code": null, "e": 2077, "s": 1983, "text": "It will become clear with the following example. We first insert a row in the customer table." }, { "code": null, "e": 2417, "s": 2077, "text": "mysql> INSERT INTO customer VALUES(1, \"John\", \"Doe\", \"M\", NULL);mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | NULL |+---------+--------+--------+--------+----------+" }, { "code": null, "e": 2536, "s": 2417, "text": "The value in the store_id column is NULL. We can update it after creating the store_id primary key in the store table." }, { "code": null, "e": 2743, "s": 2536, "text": "mysql> INSERT INTO store VALUES( -> 1, \"1234 Delaware Avenue\", \"Ashley\");mysql> INSERT INTO store VALUES(2, \"1234 West Street\", \"Max\");mysql> INSERT INTO store VALUES(3, \"1234 Kirkwood Street\", \"Emily\");" }, { "code": null, "e": 2804, "s": 2743, "text": "This retail business owns 3 stores. Here is the store table." }, { "code": null, "e": 3147, "s": 2804, "text": "mysql> select * from store;+----------+----------------------+---------+| store_id | address | manager |+----------+----------------------+---------+| 1 | 1234 Delaware Avenue | Ashley || 2 | 1234 West Street | Max || 3 | 1234 Kirkwood Street | Emily |+----------+----------------------+---------+" }, { "code": null, "e": 3226, "s": 3147, "text": "We can now update the customer table and change the store_id in the first row." }, { "code": null, "e": 3556, "s": 3226, "text": "mysql> UPDATE customer SET store_id=1 WHERE cust_id=1;mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | 1 |+---------+--------+--------+--------+----------+" }, { "code": null, "e": 3775, "s": 3556, "text": "Please note that we could have inserted data into the store table first and then into the customer table. In this way, we would not need to go back and update NULL values. I wanted to also show this way for practicing." }, { "code": null, "e": 3829, "s": 3775, "text": "Let’s add a few more customers in the customer table." }, { "code": null, "e": 4206, "s": 3829, "text": "mysql> INSERT INTO customer VALUES(2, \"Jane\", \"Doe\", \"F\", 1);mysql> INSERT INTO customer VALUES(3, \"Elaine\", \"Smith\", \"F\", 2);mysql> INSERT INTO customer VALUES(4, \"Adam\", \"Gelvin\", \"M\", 3);mysql> INSERT INTO customer VALUES(5, \"Robert\", \"Sam\", \"M\", 1);mysql> INSERT INTO customer VALUES(6, \"Betty\", \"J.\", \"F\", 2);mysql> INSERT INTO customer VALUES(7, \"Alisha\", \"T.\", \"F\", 3);" }, { "code": null, "e": 4257, "s": 4206, "text": "Here is the current version of the customer table." }, { "code": null, "e": 4827, "s": 4257, "text": "mysql> select * from customer;+---------+--------+--------+--------+----------+| cust_id | f_name | l_name | gender | store_id |+---------+--------+--------+--------+----------+| 1 | John | Doe | M | 1 || 2 | Jane | Doe | F | 1 || 3 | Elaine | Smith | F | 2 || 4 | Adam | Gelvin | M | 3 || 5 | Robert | Sam | M | 1 || 6 | Betty | J. | F | 2 || 7 | Alisha | T. | F | 3 |+---------+--------+--------+--------+----------+" }, { "code": null, "e": 4930, "s": 4827, "text": "I have populated the item and purchase tables similarly. You can come up with your own made-up values." }, { "code": null, "e": 4954, "s": 4930, "text": "Here is the item table." }, { "code": null, "e": 5639, "s": 4954, "text": "mysql> select * from item;+---------+----------------+-------+----------+| item_id | description | price | store_id |+---------+----------------+-------+----------+| 1 | apple | 2.45 | 1 || 2 | banana | 3.45 | 1 || 3 | cereal | 4.20 | 2 || 4 | milk 1 liter | 3.80 | 2 || 5 | cheddar cheese | 4.50 | 2 || 6 | icecream | 6.10 | 2 || 7 | water 2 liters | 1.10 | 3 || 8 | tomato | 0.95 | 1 || 9 | egg 15 | 4.40 | 3 || 10 | sprite 1 liter | 1.60 | 3 |+---------+----------------+-------+----------+" }, { "code": null, "e": 5680, "s": 5639, "text": "Finally, the purchase table is as below." }, { "code": null, "e": 5800, "s": 5680, "text": "The tables in the sales database contain some data now. We can retrieve all or some of the data stored in these tables." }, { "code": null, "e": 5898, "s": 5800, "text": "The SELECT statement of SQL is quite flexible so we can create simple or advanced queries easily." }, { "code": null, "e": 5987, "s": 5898, "text": "In the following examples, we will write SELECT statements to retrieve the desired data." }, { "code": null, "e": 6081, "s": 5987, "text": "We will select the cust_id column and set a condition on date column using the WHERE keyword." }, { "code": null, "e": 6282, "s": 6081, "text": "mysql> SELECT cust_id FROM purchase -> WHERE date = \"2020-05-10\";+---------+| cust_id |+---------+| 2 || 1 || 4 || 7 || 3 || 3 || 1 || 5 |+---------+" }, { "code": null, "e": 6400, "s": 6282, "text": "As you can see in the output, some IDs are repeated. We can use the DISTINCT keyword to only display unique elements." }, { "code": null, "e": 6589, "s": 6400, "text": "mysql> SELECT DISTINCT cust_id FROM purchase -> WHERE date = \"2020-05-10\";+---------+| cust_id |+---------+| 1 || 2 || 3 || 4 || 5 || 7 |+---------+" }, { "code": null, "e": 6692, "s": 6589, "text": "We will select the store_id and apply the count function. We also need to group the count by store_id." }, { "code": null, "e": 6982, "s": 6692, "text": "mysql> SELECT store_id, COUNT(store_id) FROM purchase -> GROUP BY store_id;+----------+-----------------+| store_id | COUNT(store_id) |+----------+-----------------+| 1 | 6 || 2 | 3 || 3 | 1 |+----------+-----------------+" }, { "code": null, "e": 7055, "s": 6982, "text": "We will select the price from the item table and apply the max function." }, { "code": null, "e": 7161, "s": 7055, "text": "mysql> SELECT MAX(price) FROM item;+------------+| MAX(price) |+------------+| 6.10 |+------------+" }, { "code": null, "e": 7394, "s": 7161, "text": "In the previous article, we designed and created the schema of a relational database. In this article, we have populated the tables using the INSERT statement. After, we have run some queries with SELECT statements to retrieve data." }, { "code": null, "e": 7508, "s": 7394, "text": "In the next article, I will write about creating more advanced queries. We will see the UNION and JOIN operators." }, { "code": null, "e": 7610, "s": 7508, "text": "We will also cover how to edit tables in terms of adding and removing columns and also deleting rows." } ]
MySQL SELECT IF statement with OR?
You can use SELECT IF statement with OR. To understand select with OR, let us create a table. The query to create a table is as follows − mysql> create table EmployeeInformation -> ( -> EmployeeId int, -> EmployeeName varchar(100), -> EmployeeStatus varchar(100) -> ); Query OK, 0 rows affected (0.68 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into EmployeeInformation values(1,'Sam','FullTime'); Query OK, 1 row affected (0.23 sec) mysql> insert into EmployeeInformation values(2,'Mike','PartTime'); Query OK, 1 row affected (0.14 sec) mysql> insert into EmployeeInformation values(3,'Bob','Intern'); Query OK, 1 row affected (0.14 sec) mysql> insert into EmployeeInformation values(4,'Carol','FullTime'); Query OK, 1 row affected (0.16 sec) mysql> insert into EmployeeInformation values(5,'John','FullTime'); Query OK, 1 row affected (0.19 sec) mysql> insert into EmployeeInformation values(6,'Johnson','PartTime'); Query OK, 1 row affected (0.19 sec) mysql> insert into EmployeeInformation values(7,'Maria','Intern'); Query OK, 1 row affected (0.12 sec) Let us now display all records from the table using select command. The query is as follows − mysql> select *from EmployeeInformation; +------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeStatus | +------------+--------------+----------------+ | 1 | Sam | FullTime | | 2 | Mike | PartTime | | 3 | Bob | Intern | | 4 | Carol | FullTime | | 5 | John | FullTime | | 6 | Johnson | PartTime | | 7 | Maria | Intern | +------------+--------------+----------------+ 7 rows in set (0.00 sec) Here is the query to perform SELECT IF statement with OR. In the below query, you will get only EmployeeName which has EmployeeStatus FullTime and Intern, else you will get status of the employee. The query is as follows − mysql> select if(EmployeeStatus='FullTime' or EmployeeStatus='Intern',EmployeeName,EmployeeStatus) as Status from EmployeeInformation; +----------+ | Status | +----------+ | Sam | | PartTime | | Bob | | Carol | | John | | PartTime | | Maria | +----------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1200, "s": 1062, "text": "You can use SELECT IF statement with OR. To understand select with OR, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1383, "s": 1200, "text": "mysql> create table EmployeeInformation\n -> (\n -> EmployeeId int,\n -> EmployeeName varchar(100),\n -> EmployeeStatus varchar(100)\n -> );\nQuery OK, 0 rows affected (0.68 sec)" }, { "code": null, "e": 1464, "s": 1383, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2197, "s": 1464, "text": "mysql> insert into EmployeeInformation values(1,'Sam','FullTime');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into EmployeeInformation values(2,'Mike','PartTime');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into EmployeeInformation values(3,'Bob','Intern');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into EmployeeInformation values(4,'Carol','FullTime');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into EmployeeInformation values(5,'John','FullTime');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into EmployeeInformation values(6,'Johnson','PartTime');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into EmployeeInformation values(7,'Maria','Intern');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 2291, "s": 2197, "text": "Let us now display all records from the table using select command. The query is as follows −" }, { "code": null, "e": 2332, "s": 2291, "text": "mysql> select *from EmployeeInformation;" }, { "code": null, "e": 2874, "s": 2332, "text": "+------------+--------------+----------------+\n| EmployeeId | EmployeeName | EmployeeStatus |\n+------------+--------------+----------------+\n| 1 | Sam | FullTime |\n| 2 | Mike | PartTime |\n| 3 | Bob | Intern |\n| 4 | Carol | FullTime |\n| 5 | John | FullTime |\n| 6 | Johnson | PartTime |\n| 7 | Maria | Intern |\n+------------+--------------+----------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3071, "s": 2874, "text": "Here is the query to perform SELECT IF statement with OR. In the below query, you will get only EmployeeName which has EmployeeStatus FullTime and Intern, else you will get status of the employee." }, { "code": null, "e": 3097, "s": 3071, "text": "The query is as follows −" }, { "code": null, "e": 3232, "s": 3097, "text": "mysql> select if(EmployeeStatus='FullTime' or\nEmployeeStatus='Intern',EmployeeName,EmployeeStatus) as Status from\nEmployeeInformation;" }, { "code": null, "e": 3400, "s": 3232, "text": "+----------+\n| Status |\n+----------+\n| Sam |\n| PartTime |\n| Bob |\n| Carol |\n| John |\n| PartTime |\n| Maria |\n+----------+\n7 rows in set (0.00 sec)" } ]
SAS - Linear Regression
Linear Regression is used to identify the relationship between a dependent variable and one or more independent variables. A model of the relationship is proposed, and estimates of the parameter values are used to develop an estimated regression equation. Various tests are then used to determine if the model is satisfactory. If it is then, the estimated regression equation can be used to predict the value of the dependent variable given values for the independent variables. In SAS the procedure PROC REG is used to find the linear regression model between two variables. The basic syntax for applying PROC REG in SAS is − PROC REG DATA = dataset; MODEL variable_1 = variable_2; Following is the description of the parameters used − Dataset is the name of the dataset. Dataset is the name of the dataset. variable_1 and variable_2 are the variable names of the dataset used in finding the correlation. variable_1 and variable_2 are the variable names of the dataset used in finding the correlation. The below example shows the process to find the correlation between the two variables horsepower and weight of a car by using PROC REG. In the result we see the intercept values which can be used to form the regression equation. PROC SQL; create table CARS1 as SELECT invoice, horsepower, length, weight FROM SASHELP.CARS WHERE make in ('Audi','BMW') ; RUN; proc reg data = cars1; model horsepower = weight ; run; When the above code is executed, we get the following result − The above code also gives the graphical view of various estimates of the model as shown below. Being an advanced SAS procedure it simply does not stop at giving the intercept values as the output. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2840, "s": 2583, "text": "Linear Regression is used to identify the relationship between a dependent variable and one or more independent variables. A model of the relationship is proposed, and estimates of the parameter values are used to develop an estimated regression equation." }, { "code": null, "e": 3161, "s": 2840, "text": "Various tests are then used to determine if the model is satisfactory. If it is then, the estimated regression equation can be used to predict the value of the dependent variable given values for the independent variables. In SAS the procedure PROC REG is used to find the linear regression model between two variables." }, { "code": null, "e": 3212, "s": 3161, "text": "The basic syntax for applying PROC REG in SAS is −" }, { "code": null, "e": 3269, "s": 3212, "text": "PROC REG DATA = dataset;\nMODEL variable_1 = variable_2;\n" }, { "code": null, "e": 3323, "s": 3269, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 3359, "s": 3323, "text": "Dataset is the name of the dataset." }, { "code": null, "e": 3395, "s": 3359, "text": "Dataset is the name of the dataset." }, { "code": null, "e": 3493, "s": 3395, "text": "variable_1 and variable_2 are the variable names of the dataset used in finding the correlation." }, { "code": null, "e": 3591, "s": 3493, "text": "variable_1 and variable_2 are the variable names of the dataset used in finding the correlation." }, { "code": null, "e": 3820, "s": 3591, "text": "The below example shows the process to find the correlation between the two variables horsepower and weight of a car by using PROC REG. In the result we see the intercept values which can be used to form the regression equation." }, { "code": null, "e": 4016, "s": 3820, "text": "PROC SQL;\ncreate table CARS1 as\nSELECT invoice, horsepower, length, weight\n FROM \n SASHELP.CARS\n WHERE make in ('Audi','BMW')\n;\nRUN;\nproc reg data = cars1;\nmodel horsepower = weight ;\nrun;\n" }, { "code": null, "e": 4079, "s": 4016, "text": "When the above code is executed, we get the following result −" }, { "code": null, "e": 4276, "s": 4079, "text": "The above code also gives the graphical view of various estimates of the model as shown below. Being an advanced SAS procedure it simply does not stop at giving the intercept values as the output." }, { "code": null, "e": 4311, "s": 4276, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4328, "s": 4311, "text": " Code And Create" }, { "code": null, "e": 4363, "s": 4328, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 4376, "s": 4363, "text": " Juan Galvan" }, { "code": null, "e": 4413, "s": 4376, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 4433, "s": 4413, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4468, "s": 4433, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4481, "s": 4468, "text": " Ermin Dedic" }, { "code": null, "e": 4518, "s": 4481, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 4534, "s": 4518, "text": " Muslim Helalee" }, { "code": null, "e": 4541, "s": 4534, "text": " Print" }, { "code": null, "e": 4552, "s": 4541, "text": " Add Notes" } ]
Image Grid using CSS - GeeksforGeeks
02 Nov, 2020 In this article, we will see how can we create a Diamond Grid using HTML and CSS. We will use position property to align images in a grid form. HTML part of code: In this section, we will create a structure of our grid.Approach:Create an ordered list using “ul” and add a class container.Create six “li” tags with class name.Include a “div” tag with class name bg.HTMLHTML<!DOCTYPE html><html><body> <!-- container for holding all images --><ul class="container"><!-- all li for items --> <li class="item1"> <div class="bg"></div> </li> <li class="item2"> <div class="bg"></div> </li> <li class="item3"> <div class="bg"></div> </li> <li class="item4"> <div class="bg"></div> </li> <li class="item5"> <div class="bg"></div> </li></ul></body></html> HTML part of code: In this section, we will create a structure of our grid. Approach: Create an ordered list using “ul” and add a class container.Create six “li” tags with class name.Include a “div” tag with class name bg. Create an ordered list using “ul” and add a class container. Create six “li” tags with class name. Include a “div” tag with class name bg. HTML <!DOCTYPE html><html><body> <!-- container for holding all images --><ul class="container"><!-- all li for items --> <li class="item1"> <div class="bg"></div> </li> <li class="item2"> <div class="bg"></div> </li> <li class="item3"> <div class="bg"></div> </li> <li class="item4"> <div class="bg"></div> </li> <li class="item5"> <div class="bg"></div> </li></ul></body></html> CSS: We will use CSS for setting position and assigning some style.CSSCSS/*<!-- changing background to black -->*/ *{ background-color: #000; } /* setting position of main container using general properties of CSS*/.container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px;}/*Assigning transform to each element of container for tilt*/.container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5;}/*Set opacity to one on mouse hover*/.container li:hover { opacity: 1;}/*Assigning position individually to all item of all list*/.container li.item1 { top: 0; left: 0;}.container li.item2 { bottom: 0; left: 25%;}.container li.item3 { top: 0; left: 50%;}.container li.item4 { bottom: 0; left: 75%;}.container li.item5 { top: 0; left: 100%;}/*Assigning transform to each div inside li*/.container li .bg { width: 100%; height: 100%; transform: scale(1.1);}/*Setting background image for every item*/.container li.item1 .bg { background: url(https://encrypted-tbn0. gstatic.com/ images?q=tbn%3AANd9GcT9lc92L Yah9098Udckm8qbObhSx3cq TCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item4 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} CSS: We will use CSS for setting position and assigning some style. CSS /*<!-- changing background to black -->*/ *{ background-color: #000; } /* setting position of main container using general properties of CSS*/.container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px;}/*Assigning transform to each element of container for tilt*/.container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5;}/*Set opacity to one on mouse hover*/.container li:hover { opacity: 1;}/*Assigning position individually to all item of all list*/.container li.item1 { top: 0; left: 0;}.container li.item2 { bottom: 0; left: 25%;}.container li.item3 { top: 0; left: 50%;}.container li.item4 { bottom: 0; left: 75%;}.container li.item5 { top: 0; left: 100%;}/*Assigning transform to each div inside li*/.container li .bg { width: 100%; height: 100%; transform: scale(1.1);}/*Setting background image for every item*/.container li.item1 .bg { background: url(https://encrypted-tbn0. gstatic.com/ images?q=tbn%3AANd9GcT9lc92L Yah9098Udckm8qbObhSx3cq TCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item4 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} Complete Code: HTML <!DOCTYPE html><html> <style> /* Changing background to black */ * { background-color: #000; } /* setting position of main container using general properties of CSS */ .container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px; } /* Assigning transform to each element of container for tilt */ .container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5; } /* Set opacity to one on mouse hover */ .container li:hover { opacity: 1; } /* Assigning position individually to all item of all list */ .container li.item1 { top: 0; left: 0; } .container li.item2 { bottom: 0; left: 25%; } .container li.item3 { top: 0; left: 50%; } .container li.item4 { bottom: 0; left: 75%; } .container li.item5 { top: 0; left: 100%; } /* Assigning transform to each div inside li */ .container li .bg { width: 100%; height: 100%; transform: scale(1.1); } /* Setting background image for every item */ .container li.item1 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png); background-size: cover; background-position: center; } .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } .container li.item4 .bg { background: url( https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png); background-size: cover; background-position: center; } .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } </style> <body> <!-- Container for holding all images --> <ul class="container"> <!-- All li for items --> <li class="item1"> <div class="bg"></div> </li> <li class="item2"> <div class="bg"></div> </li> <li class="item3"> <div class="bg"></div> </li> <li class="item4"> <div class="bg"></div> </li> <li class="item5"> <div class="bg"></div> </li> </ul> </body></html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Basics HTML-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25122, "s": 25094, "text": "\n02 Nov, 2020" }, { "code": null, "e": 25266, "s": 25122, "text": "In this article, we will see how can we create a Diamond Grid using HTML and CSS. We will use position property to align images in a grid form." }, { "code": null, "e": 25894, "s": 25266, "text": "HTML part of code: In this section, we will create a structure of our grid.Approach:Create an ordered list using “ul” and add a class container.Create six “li” tags with class name.Include a “div” tag with class name bg.HTMLHTML<!DOCTYPE html><html><body> <!-- container for holding all images --><ul class=\"container\"><!-- all li for items --> <li class=\"item1\"> <div class=\"bg\"></div> </li> <li class=\"item2\"> <div class=\"bg\"></div> </li> <li class=\"item3\"> <div class=\"bg\"></div> </li> <li class=\"item4\"> <div class=\"bg\"></div> </li> <li class=\"item5\"> <div class=\"bg\"></div> </li></ul></body></html>" }, { "code": null, "e": 25970, "s": 25894, "text": "HTML part of code: In this section, we will create a structure of our grid." }, { "code": null, "e": 25980, "s": 25970, "text": "Approach:" }, { "code": null, "e": 26117, "s": 25980, "text": "Create an ordered list using “ul” and add a class container.Create six “li” tags with class name.Include a “div” tag with class name bg." }, { "code": null, "e": 26178, "s": 26117, "text": "Create an ordered list using “ul” and add a class container." }, { "code": null, "e": 26216, "s": 26178, "text": "Create six “li” tags with class name." }, { "code": null, "e": 26256, "s": 26216, "text": "Include a “div” tag with class name bg." }, { "code": null, "e": 26261, "s": 26256, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <!-- container for holding all images --><ul class=\"container\"><!-- all li for items --> <li class=\"item1\"> <div class=\"bg\"></div> </li> <li class=\"item2\"> <div class=\"bg\"></div> </li> <li class=\"item3\"> <div class=\"bg\"></div> </li> <li class=\"item4\"> <div class=\"bg\"></div> </li> <li class=\"item5\"> <div class=\"bg\"></div> </li></ul></body></html>", "e": 26661, "s": 26261, "text": null }, { "code": null, "e": 28907, "s": 26661, "text": "CSS: We will use CSS for setting position and assigning some style.CSSCSS/*<!-- changing background to black -->*/ *{ background-color: #000; } /* setting position of main container using general properties of CSS*/.container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px;}/*Assigning transform to each element of container for tilt*/.container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5;}/*Set opacity to one on mouse hover*/.container li:hover { opacity: 1;}/*Assigning position individually to all item of all list*/.container li.item1 { top: 0; left: 0;}.container li.item2 { bottom: 0; left: 25%;}.container li.item3 { top: 0; left: 50%;}.container li.item4 { bottom: 0; left: 75%;}.container li.item5 { top: 0; left: 100%;}/*Assigning transform to each div inside li*/.container li .bg { width: 100%; height: 100%; transform: scale(1.1);}/*Setting background image for every item*/.container li.item1 .bg { background: url(https://encrypted-tbn0. gstatic.com/ images?q=tbn%3AANd9GcT9lc92L Yah9098Udckm8qbObhSx3cq TCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item4 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;}" }, { "code": null, "e": 28975, "s": 28907, "text": "CSS: We will use CSS for setting position and assigning some style." }, { "code": null, "e": 28979, "s": 28975, "text": "CSS" }, { "code": "/*<!-- changing background to black -->*/ *{ background-color: #000; } /* setting position of main container using general properties of CSS*/.container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px;}/*Assigning transform to each element of container for tilt*/.container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5;}/*Set opacity to one on mouse hover*/.container li:hover { opacity: 1;}/*Assigning position individually to all item of all list*/.container li.item1 { top: 0; left: 0;}.container li.item2 { bottom: 0; left: 25%;}.container li.item3 { top: 0; left: 50%;}.container li.item4 { bottom: 0; left: 75%;}.container li.item5 { top: 0; left: 100%;}/*Assigning transform to each div inside li*/.container li .bg { width: 100%; height: 100%; transform: scale(1.1);}/*Setting background image for every item*/.container li.item1 .bg { background: url(https://encrypted-tbn0. gstatic.com/ images?q=tbn%3AANd9GcT9lc92L Yah9098Udckm8qbObhSx3cq TCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;} .container li.item4 .bg { background: url(https://www.geeksforgeeks.org/ wp-content/ uploads/gfg_200X200-1.png); background-size: cover; background-position: center;} .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/ images?q=tbn%3AANd9GcT9lc92LYah9098Udc km8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center;}", "e": 31152, "s": 28979, "text": null }, { "code": null, "e": 31167, "s": 31152, "text": "Complete Code:" }, { "code": null, "e": 31172, "s": 31167, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <style> /* Changing background to black */ * { background-color: #000; } /* setting position of main container using general properties of CSS */ .container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; padding: 0; width: 600px; height: 150px; } /* Assigning transform to each element of container for tilt */ .container li { list-style: none; position: absolute; width: 200px; height: 200px; background: #000; transform: rotate(45deg); transition: 0.5s; margin: -100px; overflow: hidden; opacity: 0.5; } /* Set opacity to one on mouse hover */ .container li:hover { opacity: 1; } /* Assigning position individually to all item of all list */ .container li.item1 { top: 0; left: 0; } .container li.item2 { bottom: 0; left: 25%; } .container li.item3 { top: 0; left: 50%; } .container li.item4 { bottom: 0; left: 75%; } .container li.item5 { top: 0; left: 100%; } /* Assigning transform to each div inside li */ .container li .bg { width: 100%; height: 100%; transform: scale(1.1); } /* Setting background image for every item */ .container li.item1 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } .container li.item2 .bg { background: url(https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png); background-size: cover; background-position: center; } .container li.item3 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } .container li.item4 .bg { background: url( https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png); background-size: cover; background-position: center; } .container li.item5 .bg { background: url(https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT9lc92LYah9098Udckm8qbObhSx3cqTCyEvQ&usqp=CAU); background-size: cover; background-position: center; } </style> <body> <!-- Container for holding all images --> <ul class=\"container\"> <!-- All li for items --> <li class=\"item1\"> <div class=\"bg\"></div> </li> <li class=\"item2\"> <div class=\"bg\"></div> </li> <li class=\"item3\"> <div class=\"bg\"></div> </li> <li class=\"item4\"> <div class=\"bg\"></div> </li> <li class=\"item5\"> <div class=\"bg\"></div> </li> </ul> </body></html>", "e": 34679, "s": 31172, "text": null }, { "code": null, "e": 34687, "s": 34679, "text": "Output:" }, { "code": null, "e": 34824, "s": 34687, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34835, "s": 34824, "text": "CSS-Basics" }, { "code": null, "e": 34847, "s": 34835, "text": "HTML-Basics" }, { "code": null, "e": 34851, "s": 34847, "text": "CSS" }, { "code": null, "e": 34856, "s": 34851, "text": "HTML" }, { "code": null, "e": 34873, "s": 34856, "text": "Web Technologies" }, { "code": null, "e": 34878, "s": 34873, "text": "HTML" }, { "code": null, "e": 34976, "s": 34878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34985, "s": 34976, "text": "Comments" }, { "code": null, "e": 34998, "s": 34985, "text": "Old Comments" }, { "code": null, "e": 35056, "s": 34998, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 35093, "s": 35056, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 35157, "s": 35093, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 35198, "s": 35157, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 35235, "s": 35198, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 35295, "s": 35235, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35356, "s": 35295, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 35409, "s": 35356, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35459, "s": 35409, "text": "How to Insert Form Data into Database using PHP ?" } ]
Puppet - Installation
Puppet works on the client server architecture, wherein we call the server as the Puppet master and the client as the Puppet node. This setup is achieved by installing Puppet on both the client and well as on all the server machines. For most of the platforms, Puppet can be installed via the package manager of choice. However, for few platforms it can be done by installing the tarball or RubyGems. Factor is the only pre-requisite that does not come along with Ohai which is present in Chef. We need to have standard set of library of any underlying OS. Remaining all the system comes along with Ruby 1.8.2 + versions. Following is the list of library items, which an OS should consist of. base64 cgi digest/md5 etc fileutils ipaddr openssl strscan syslog uri webrick webrick/https xmlrpc As discussed, the facter does not come along with the standard edition of Ruby. So, in order to get the facter in the target system one needs to install it manually from the source as the facter library is a pre-requisite of Puppet. This package is available for multiple platforms however just to be on the safer side it can be installed using tarball, which helps in getting the latest version. First, download the tarball from the official site of Puppet using the wget utility. $ wget http://puppetlabs.com/downloads/facter/facter-latest.tgz ------: 1 Next, un-tar the tar file. Get inside the untarred directory using the CD command. Finally, install the facter using install.rb file present inside the facter directory. $ gzip -d -c facter-latest.tgz | tar xf - -----: 2 $ cd facter-* ------: 3 $ sudo ruby install.rb # or become root and run install.rb -----:4 First, install the Puppet tarball from the Puppet site using wget. Then, extract the tarball to a target location. Move inside the created directory using the CD command. Using install.rb file, install Puppet on the underlying server. # get the latest tarball $ wget http://puppetlabs.com/downloads/puppet/puppet-latest.tgz -----: 1 # untar and install it $ gzip -d -c puppet-latest.tgz | tar xf - ----: 2 $ cd puppet-* ------: 3 $ sudo ruby install.rb # or become root and run install.rb -------: 4 # Installing Facter $ wget http://puppetlabs.com/downloads/gems/facter-1.5.7.gem $ sudo gem install facter-1.5.7.gem # Installing Puppet $ wget http://puppetlabs.com/downloads/gems/puppet-0.25.1.gem $ sudo gem install puppet-0.25.1.gem Print Add Notes Bookmark this page
[ { "code": null, "e": 2407, "s": 2173, "text": "Puppet works on the client server architecture, wherein we call the server as the Puppet master and the client as the Puppet node. This setup is achieved by installing Puppet on both the client and well as on all the server machines." }, { "code": null, "e": 2574, "s": 2407, "text": "For most of the platforms, Puppet can be installed via the package manager of choice. However, for few platforms it can be done by installing the tarball or RubyGems." }, { "code": null, "e": 2668, "s": 2574, "text": "Factor is the only pre-requisite that does not come along with Ohai which is present in Chef." }, { "code": null, "e": 2866, "s": 2668, "text": "We need to have standard set of library of any underlying OS. Remaining all the system comes along with Ruby 1.8.2 + versions. Following is the list of library items, which an OS should consist of." }, { "code": null, "e": 2873, "s": 2866, "text": "base64" }, { "code": null, "e": 2877, "s": 2873, "text": "cgi" }, { "code": null, "e": 2888, "s": 2877, "text": "digest/md5" }, { "code": null, "e": 2892, "s": 2888, "text": "etc" }, { "code": null, "e": 2902, "s": 2892, "text": "fileutils" }, { "code": null, "e": 2909, "s": 2902, "text": "ipaddr" }, { "code": null, "e": 2917, "s": 2909, "text": "openssl" }, { "code": null, "e": 2925, "s": 2917, "text": "strscan" }, { "code": null, "e": 2932, "s": 2925, "text": "syslog" }, { "code": null, "e": 2936, "s": 2932, "text": "uri" }, { "code": null, "e": 2944, "s": 2936, "text": "webrick" }, { "code": null, "e": 2958, "s": 2944, "text": "webrick/https" }, { "code": null, "e": 2965, "s": 2958, "text": "xmlrpc" }, { "code": null, "e": 3198, "s": 2965, "text": "As discussed, the facter does not come along with the standard edition of Ruby. So, in order to get the facter in the target system one needs to install it manually from the source as the facter library is a pre-requisite of Puppet." }, { "code": null, "e": 3362, "s": 3198, "text": "This package is available for multiple platforms however just to be on the safer side it can be installed using tarball, which helps in getting the latest version." }, { "code": null, "e": 3447, "s": 3362, "text": "First, download the tarball from the official site of Puppet using the wget utility." }, { "code": null, "e": 3524, "s": 3447, "text": "$ wget http://puppetlabs.com/downloads/facter/facter-latest.tgz ------: 1 \n" }, { "code": null, "e": 3694, "s": 3524, "text": "Next, un-tar the tar file. Get inside the untarred directory using the CD command. Finally, install the facter using install.rb file present inside the facter directory." }, { "code": null, "e": 3840, "s": 3694, "text": "$ gzip -d -c facter-latest.tgz | tar xf - -----: 2 \n$ cd facter-* ------: 3 \n$ sudo ruby install.rb # or become root and run install.rb -----:4 \n" }, { "code": null, "e": 4075, "s": 3840, "text": "First, install the Puppet tarball from the Puppet site using wget. Then, extract the tarball to a target location. Move inside the created directory using the CD command. Using install.rb file, install Puppet on the underlying server." }, { "code": null, "e": 4347, "s": 4075, "text": "# get the latest tarball \n$ wget http://puppetlabs.com/downloads/puppet/puppet-latest.tgz -----: 1\n\n# untar and install it \n$ gzip -d -c puppet-latest.tgz | tar xf - ----: 2 \n$ cd puppet-* ------: 3 \n$ sudo ruby install.rb # or become root and run install.rb -------: 4 \n" }, { "code": null, "e": 4590, "s": 4347, "text": "# Installing Facter \n$ wget http://puppetlabs.com/downloads/gems/facter-1.5.7.gem \n$ sudo gem install facter-1.5.7.gem\n\n# Installing Puppet \n$ wget http://puppetlabs.com/downloads/gems/puppet-0.25.1.gem \n$ sudo gem install puppet-0.25.1.gem \n" }, { "code": null, "e": 4597, "s": 4590, "text": " Print" }, { "code": null, "e": 4608, "s": 4597, "text": " Add Notes" } ]
Java Swing | BevelBorder and SoftBevelBorder - GeeksforGeeks
16 Apr, 2021 BevelBorder and SoftBevelBorder are a part of javax.swing.Border package. This package contains different Border for Components. BevelBorder is an implementation of a simple two line bevel border. Bevel Border and Soft Bevel Border are almost same but Soft Bevel Border has softened corners.Constructor for the class BevelBorder: BevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.BevelBorder(int Type, Color h, Color s):Creates a bevel border with the specified type, highlight and shadow colors.BevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor):Creates a bevel border with the specified type, highlight and shadow colors. BevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method. BevelBorder(int Type, Color h, Color s):Creates a bevel border with the specified type, highlight and shadow colors. BevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor):Creates a bevel border with the specified type, highlight and shadow colors. Constructor for the class SoftBevelBorder: SoftBevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.SoftBevelBorder(int Type, Color h, Color s): Creates a bevel border with the specified type, highlight and shadow colors.SoftBevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor): Creates a bevel border with the specified type, highlight and shadow colors. SoftBevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method. SoftBevelBorder(int Type, Color h, Color s): Creates a bevel border with the specified type, highlight and shadow colors. SoftBevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor): Creates a bevel border with the specified type, highlight and shadow colors. Commonly used methods are: Below programs illustrate the Bevel Border class: Program to create a simple bevel border with specified type: To create a bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Program to create a simple bevel border with specified type: To create a bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Java // Java Program to create a simple bevel// border with specified typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object bevel s = new bevel(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(" this is bevel border of raised type"); // create a label JLabel l1 = new JLabel(" this is bevel border of lowered type"); // set border for panel l.setBorder(new BevelBorder(BevelBorder.RAISED)); // set border for label l1.setBorder(new BevelBorder(BevelBorder.LOWERED)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }} Output: Output: Program to apply bevel border with specified colors to highlight and shadow: To create a bevel border with highlighted colors, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). And the colors are passed into these constructors as parameters, for ex: Color.red etc.) Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Program to apply bevel border with specified colors to highlight and shadow: To create a bevel border with highlighted colors, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). And the colors are passed into these constructors as parameters, for ex: Color.red etc.) Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Java // java Program to apply bevel border with// specified colors to highlight and shadowimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel1 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object bevel1 s = new bevel1(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(" this is bevel border of raised type"); // create a label JLabel l1 = new JLabel(" this is bevel border of lowered type"); // set border for panel l.setBorder(new BevelBorder(BevelBorder.RAISED, Color.red, Color.blue)); // set border for label l1.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.black, Color.red, Color.pink, Color.yellow)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }} Output: Output: Below programs illustrate the SoftBevelBorder class: Program to create a simple Soft bevel border with specified type: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Program to create a simple Soft bevel border with specified type: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Java // java Program to create a simple Soft bevel border// with specified typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel2 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object bevel2 s = new bevel2(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(" this is bevel border of raised type"); // create a label JLabel l1 = new JLabel(" this is bevel border of lowered type"); // set border for panel l.setBorder(new SoftBevelBorder(BevelBorder.RAISED)); // set border for label l1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }} Output: Output: Program to apply soft bevel border with specified colors to highlight and shadow: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). And the colors are passed into these constructors as parameters, for ex: Color.red etc.). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Program to apply soft bevel border with specified colors to highlight and shadow: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). And the colors are passed into these constructors as parameters, for ex: Color.red etc.). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). Java // Java Program to apply soft bevel border with// specified colors to highlight and shadowimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel3 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // create a object bevel3 s = new bevel3(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(" this is bevel border of raised type"); // create a label JLabel l1 = new JLabel(" this is bevel border of lowered type"); // set border for panel l.setBorder(new SoftBevelBorder(BevelBorder.RAISED, Color.red, Color.blue)); // set border for label l1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.black, Color.red, Color.pink, Color.yellow)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }} Output: Output: Note: The above programs might not run in an online IDE please use an offline compile.Reference: https://docs.oracle.com/javase/7/docs/api/javax/swing/border/BevelBorder.html https://docs.oracle.com/javase/7/docs/api/javax/swing/border/SoftBevelBorder.html Akanksha_Rai ManasChhabra2 sweetyty java-swing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 24478, "s": 24450, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24810, "s": 24478, "text": "BevelBorder and SoftBevelBorder are a part of javax.swing.Border package. This package contains different Border for Components. BevelBorder is an implementation of a simple two line bevel border. Bevel Border and Soft Bevel Border are almost same but Soft Bevel Border has softened corners.Constructor for the class BevelBorder: " }, { "code": null, "e": 25308, "s": 24810, "text": "BevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.BevelBorder(int Type, Color h, Color s):Creates a bevel border with the specified type, highlight and shadow colors.BevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor):Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 25490, "s": 25308, "text": "BevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method." }, { "code": null, "e": 25607, "s": 25490, "text": "BevelBorder(int Type, Color h, Color s):Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 25808, "s": 25607, "text": "BevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor):Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 25853, "s": 25808, "text": "Constructor for the class SoftBevelBorder: " }, { "code": null, "e": 26365, "s": 25853, "text": "SoftBevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.SoftBevelBorder(int Type, Color h, Color s): Creates a bevel border with the specified type, highlight and shadow colors.SoftBevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor): Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 26551, "s": 26365, "text": "SoftBevelBorder(int Type): Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method." }, { "code": null, "e": 26673, "s": 26551, "text": "SoftBevelBorder(int Type, Color h, Color s): Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 26879, "s": 26673, "text": "SoftBevelBorder(int Type, Color highlightOuterColor, Color highlightInnerColor, Color shadowOuterColor, Color shadowInnerColor): Creates a bevel border with the specified type, highlight and shadow colors." }, { "code": null, "e": 26907, "s": 26879, "text": "Commonly used methods are: " }, { "code": null, "e": 26961, "s": 26909, "text": "Below programs illustrate the Bevel Border class: " }, { "code": null, "e": 27544, "s": 26961, "text": "Program to create a simple bevel border with specified type: To create a bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 28127, "s": 27544, "text": "Program to create a simple bevel border with specified type: To create a bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 28132, "s": 28127, "text": "Java" }, { "code": "// Java Program to create a simple bevel// border with specified typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object bevel s = new bevel(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\" this is bevel border of raised type\"); // create a label JLabel l1 = new JLabel(\" this is bevel border of lowered type\"); // set border for panel l.setBorder(new BevelBorder(BevelBorder.RAISED)); // set border for label l1.setBorder(new BevelBorder(BevelBorder.LOWERED)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }}", "e": 29138, "s": 28132, "text": null }, { "code": null, "e": 29148, "s": 29138, "text": "Output: " }, { "code": null, "e": 29158, "s": 29148, "text": "Output: " }, { "code": null, "e": 29871, "s": 29158, "text": " Program to apply bevel border with specified colors to highlight and shadow: To create a bevel border with highlighted colors, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). And the colors are passed into these constructors as parameters, for ex: Color.red etc.) Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 30585, "s": 29873, "text": "Program to apply bevel border with specified colors to highlight and shadow: To create a bevel border with highlighted colors, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f, which is the outermost container in this program. To set the bevel border, we create 2 JLabel objects, “l” and “l1”, one for the raised type border and the other for lowered type border. The borders are applied by the function l.setBorder() and l1.setBorder(). And the colors are passed into these constructors as parameters, for ex: Color.red etc.) Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 30590, "s": 30585, "text": "Java" }, { "code": "// java Program to apply bevel border with// specified colors to highlight and shadowimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel1 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object bevel1 s = new bevel1(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\" this is bevel border of raised type\"); // create a label JLabel l1 = new JLabel(\" this is bevel border of lowered type\"); // set border for panel l.setBorder(new BevelBorder(BevelBorder.RAISED, Color.red, Color.blue)); // set border for label l1.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.black, Color.red, Color.pink, Color.yellow)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }}", "e": 31776, "s": 30590, "text": null }, { "code": null, "e": 31786, "s": 31776, "text": "Output: " }, { "code": null, "e": 31796, "s": 31786, "text": "Output: " }, { "code": null, "e": 31851, "s": 31796, "text": "Below programs illustrate the SoftBevelBorder class: " }, { "code": null, "e": 32465, "s": 31851, "text": "Program to create a simple Soft bevel border with specified type: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 33079, "s": 32465, "text": "Program to create a simple Soft bevel border with specified type: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 33084, "s": 33079, "text": "Java" }, { "code": "// java Program to create a simple Soft bevel border// with specified typeimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel2 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object bevel2 s = new bevel2(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\" this is bevel border of raised type\"); // create a label JLabel l1 = new JLabel(\" this is bevel border of lowered type\"); // set border for panel l.setBorder(new SoftBevelBorder(BevelBorder.RAISED)); // set border for label l1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }}", "e": 34106, "s": 33084, "text": null }, { "code": null, "e": 34116, "s": 34106, "text": "Output: " }, { "code": null, "e": 34126, "s": 34116, "text": "Output: " }, { "code": null, "e": 34847, "s": 34126, "text": " Program to apply soft bevel border with specified colors to highlight and shadow: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). And the colors are passed into these constructors as parameters, for ex: Color.red etc.). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 35569, "s": 34849, "text": "Program to apply soft bevel border with specified colors to highlight and shadow: To create a soft bevel border, we first create a JPanel object p, all the borders will be applied to this object. The JPanel will be hosted inside the JFrame f. To set the bevel border, we create 2 JLabel objects, “l” and “l1”. The borders are applied by the function l.setBorder() and l1.setBorder(). To make the border soft, we call the constructor in the parameter of setBorder() method, which is indicated by line “new SoftBevelBorder()). And the colors are passed into these constructors as parameters, for ex: Color.red etc.). Finally, the borders are added to the JPanel by p.add() function and the results are shown by f.show(). " }, { "code": null, "e": 35574, "s": 35569, "text": "Java" }, { "code": "// Java Program to apply soft bevel border with// specified colors to highlight and shadowimport java.awt.event.*;import java.awt.*;import javax.swing.*;import javax.swing.border.*;class bevel3 extends JFrame { // frame static JFrame f; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // create a object bevel3 s = new bevel3(); // create a panel JPanel p = new JPanel(); // create a label JLabel l = new JLabel(\" this is bevel border of raised type\"); // create a label JLabel l1 = new JLabel(\" this is bevel border of lowered type\"); // set border for panel l.setBorder(new SoftBevelBorder(BevelBorder.RAISED, Color.red, Color.blue)); // set border for label l1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.black, Color.red, Color.pink, Color.yellow)); // add button to panel p.add(l1); p.add(l); f.add(p); // set the size of frame f.setSize(400, 400); f.show(); }}", "e": 36777, "s": 35574, "text": null }, { "code": null, "e": 36787, "s": 36777, "text": "Output: " }, { "code": null, "e": 36797, "s": 36787, "text": "Output: " }, { "code": null, "e": 36896, "s": 36797, "text": "Note: The above programs might not run in an online IDE please use an offline compile.Reference: " }, { "code": null, "e": 36974, "s": 36896, "text": "https://docs.oracle.com/javase/7/docs/api/javax/swing/border/BevelBorder.html" }, { "code": null, "e": 37056, "s": 36974, "text": "https://docs.oracle.com/javase/7/docs/api/javax/swing/border/SoftBevelBorder.html" }, { "code": null, "e": 37071, "s": 37058, "text": "Akanksha_Rai" }, { "code": null, "e": 37085, "s": 37071, "text": "ManasChhabra2" }, { "code": null, "e": 37094, "s": 37085, "text": "sweetyty" }, { "code": null, "e": 37105, "s": 37094, "text": "java-swing" }, { "code": null, "e": 37110, "s": 37105, "text": "Java" }, { "code": null, "e": 37115, "s": 37110, "text": "Java" }, { "code": null, "e": 37213, "s": 37115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37245, "s": 37213, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 37296, "s": 37245, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 37326, "s": 37296, "text": "HashMap in Java with Examples" }, { "code": null, "e": 37345, "s": 37326, "text": "Interfaces in Java" }, { "code": null, "e": 37363, "s": 37345, "text": "ArrayList in Java" }, { "code": null, "e": 37394, "s": 37363, "text": "How to iterate any Map in Java" }, { "code": null, "e": 37426, "s": 37394, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37446, "s": 37426, "text": "Stack Class in Java" }, { "code": null, "e": 37461, "s": 37446, "text": "Stream In Java" } ]
Angular PrimeNG Chip Component - GeeksforGeeks
24 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Chip component in Angular PrimeNG. Chip component: It is used to represent icons, labels, and images. Properties: label: It is used to define the text to display. It is of string data type, the default value is null. icon: It is used to define the icon to display. It is of string data type, the default value is null. image: It is used to define the image to display. It is of string data type, the default value is null. removable: It is used to define whether to display a remove icon. It is of boolean data type, the default value is false. style: It is used to set the inline style of the component. It is of object data type, the default value is null. styleClass: It is used to define the style class of the component. It is of string data type, the default value is null. removeIcon: It is the icon of the remove element. It is of string data type, the default value is pi pi-times-circle. Styling: p-chip: It is the container styling element. p-chip-image: It is the container element in image mode. p-chip-text: It styles the text of the chip. pi-chip-remove-icon: It styles the remove icon. Events: onRemove: It is a callback function that is invoked when a chip is removed. Creating Angular application & module installation: Step 1: Create an Angular application using the following command.ng new appname Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory.npm install primeng --save npm install primeicons --save Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use a Chip component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Chip Component</h5><div class="p-d-flex p-ai-center"> <p-chip label="A" styleClass="p-mr-1"></p-chip> <p-chip label="B" styleClass="p-mr-1"></p-chip> <p-chip label="C" styleClass="p-mr-1"></p-chip> <p-chip label="D" styleClass="p-mr-1"></p-chip> <p-chip label="E" styleClass="p-mr-1"></p-chip> <p-chip label="F"></p-chip></div> app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { ChipModule } from "primeng/chip"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ChipModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we will know how to use removable and icon properties in the Chip component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG Chip Component</h5><div class="p-d-flex p-ai-center"> <p-chip label="A" removable="true" styleClass="p-mr-1" icon="pi pi-angle-double-left"> </p-chip> <p-chip label="B" icon="pi pi-angle-left " removable="true" styleClass="p-mr-1"> </p-chip> <p-chip label="C" icon="pi pi-bars" removable="true" styleClass="p-mr-1"> </p-chip> <p-chip label="D" icon="pi pi-angle-right" removable="true" styleClass="p-mr-1"> </p-chip> <p-chip label="E" icon="pi pi-angle-double-right" removable="true" styleClass="p-mr-1"> </p-chip></div> app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { ChipModule } from "primeng/chip"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ChipModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/chip Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n24 Aug, 2021" }, { "code": null, "e": 25389, "s": 25109, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Chip component in Angular PrimeNG." }, { "code": null, "e": 25456, "s": 25389, "text": "Chip component: It is used to represent icons, labels, and images." }, { "code": null, "e": 25468, "s": 25456, "text": "Properties:" }, { "code": null, "e": 25571, "s": 25468, "text": "label: It is used to define the text to display. It is of string data type, the default value is null." }, { "code": null, "e": 25673, "s": 25571, "text": "icon: It is used to define the icon to display. It is of string data type, the default value is null." }, { "code": null, "e": 25777, "s": 25673, "text": "image: It is used to define the image to display. It is of string data type, the default value is null." }, { "code": null, "e": 25899, "s": 25777, "text": "removable: It is used to define whether to display a remove icon. It is of boolean data type, the default value is false." }, { "code": null, "e": 26013, "s": 25899, "text": "style: It is used to set the inline style of the component. It is of object data type, the default value is null." }, { "code": null, "e": 26134, "s": 26013, "text": "styleClass: It is used to define the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 26252, "s": 26134, "text": "removeIcon: It is the icon of the remove element. It is of string data type, the default value is pi pi-times-circle." }, { "code": null, "e": 26261, "s": 26252, "text": "Styling:" }, { "code": null, "e": 26306, "s": 26261, "text": "p-chip: It is the container styling element." }, { "code": null, "e": 26363, "s": 26306, "text": "p-chip-image: It is the container element in image mode." }, { "code": null, "e": 26408, "s": 26363, "text": "p-chip-text: It styles the text of the chip." }, { "code": null, "e": 26456, "s": 26408, "text": "pi-chip-remove-icon: It styles the remove icon." }, { "code": null, "e": 26466, "s": 26458, "text": "Events:" }, { "code": null, "e": 26542, "s": 26466, "text": "onRemove: It is a callback function that is invoked when a chip is removed." }, { "code": null, "e": 26594, "s": 26542, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 26675, "s": 26594, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 26742, "s": 26675, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 26757, "s": 26742, "text": "ng new appname" }, { "code": null, "e": 26864, "s": 26757, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 26961, "s": 26864, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 26972, "s": 26961, "text": "cd appname" }, { "code": null, "e": 27077, "s": 26972, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 27126, "s": 27077, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 27183, "s": 27126, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 27235, "s": 27183, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 27314, "s": 27237, "text": "Example 1: This is the basic example that shows how to use a Chip component." }, { "code": null, "e": 27333, "s": 27314, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Chip Component</h5><div class=\"p-d-flex p-ai-center\"> <p-chip label=\"A\" styleClass=\"p-mr-1\"></p-chip> <p-chip label=\"B\" styleClass=\"p-mr-1\"></p-chip> <p-chip label=\"C\" styleClass=\"p-mr-1\"></p-chip> <p-chip label=\"D\" styleClass=\"p-mr-1\"></p-chip> <p-chip label=\"E\" styleClass=\"p-mr-1\"></p-chip> <p-chip label=\"F\"></p-chip></div>", "e": 27701, "s": 27333, "text": null }, { "code": null, "e": 27715, "s": 27701, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { AppComponent } from \"./app.component\";import { ChipModule } from \"primeng/chip\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ChipModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 28180, "s": 27715, "text": null }, { "code": null, "e": 28188, "s": 28180, "text": "Output:" }, { "code": null, "e": 28293, "s": 28188, "text": "Example 2: In this example, we will know how to use removable and icon properties in the Chip component." }, { "code": null, "e": 28312, "s": 28293, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Chip Component</h5><div class=\"p-d-flex p-ai-center\"> <p-chip label=\"A\" removable=\"true\" styleClass=\"p-mr-1\" icon=\"pi pi-angle-double-left\"> </p-chip> <p-chip label=\"B\" icon=\"pi pi-angle-left \" removable=\"true\" styleClass=\"p-mr-1\"> </p-chip> <p-chip label=\"C\" icon=\"pi pi-bars\" removable=\"true\" styleClass=\"p-mr-1\"> </p-chip> <p-chip label=\"D\" icon=\"pi pi-angle-right\" removable=\"true\" styleClass=\"p-mr-1\"> </p-chip> <p-chip label=\"E\" icon=\"pi pi-angle-double-right\" removable=\"true\" styleClass=\"p-mr-1\"> </p-chip></div>", "e": 28958, "s": 28312, "text": null }, { "code": null, "e": 28972, "s": 28958, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { AppComponent } from \"./app.component\";import { ChipModule } from \"primeng/chip\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ChipModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 29433, "s": 28972, "text": null }, { "code": null, "e": 29441, "s": 29433, "text": "Output:" }, { "code": null, "e": 29499, "s": 29441, "text": "Reference: https://primefaces.org/primeng/showcase/#/chip" }, { "code": null, "e": 29515, "s": 29499, "text": "Angular-PrimeNG" }, { "code": null, "e": 29525, "s": 29515, "text": "AngularJS" }, { "code": null, "e": 29542, "s": 29525, "text": "Web Technologies" }, { "code": null, "e": 29640, "s": 29542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29649, "s": 29640, "text": "Comments" }, { "code": null, "e": 29662, "s": 29649, "text": "Old Comments" }, { "code": null, "e": 29706, "s": 29662, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29770, "s": 29706, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 29823, "s": 29770, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 29847, "s": 29823, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 29882, "s": 29847, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29924, "s": 29882, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29957, "s": 29924, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30000, "s": 29957, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30062, "s": 30000, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Adding a DeleteView in Django
DeleteView is a view in Django which is used to delete any model data from the frontend. It is a built-in view that can be easily applied. It acts like admin page in deleting the view. It is really helpful in real-world projects. First of all, create a Django project and an app. I created the project with the name "tutorial11" and the app with the name "modelFormsDemo". Now, let's do some basic things. Add the app in settings.py − INSTALLED_APPS+ = ['modelFormsDemo'] In project's urls.py − from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('modelFormsDemo.urls')) ] Here we included the app's url. In app's urls.py − from django.urls import path,include from . import views urlpatterns = [ path('', views.home,name="home"), path('student/delete//', views.StudentDeleteView. as_view(),name="delete"), path('success/',views.success,name='success') ] Here we created 3 URLs: one for rendering the frontend, DeleteView for deleting, and Success for redirecting after deleting. In models.py, add this − from django.db import models # Create your models here. class Student(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100) Here we created a simple model. In views.py, add the following − from django.shortcuts import render from .forms import StudentForm from django.views.generic.edit import DeleteView from .models import Student from django.urls import reverse_lazy # Create your views here. def home(request): if request.method=='POST': form=StudentForm(request.POST) if form.is_valid(): form.save() stuForm=StudentForm() return render(request,'home.html',{"stu_form":stuForm}) class StudentDeleteView(DeleteView): model=Student template_name='delete_view.html' success_url=reverse_lazy("success") Here, in home view, we rendered the frontend and in DeleteView, we rendered the delete_view.html which will ask for delete confirmation. Create forms.py in app directory and write this − from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model=Student fields=['name', 'standard', 'section'] Here we created our simple form which we will render in home view. Now create a templates folder and add three files inside it home.html, delete_view.html and success.html. In home.html − <!DOCTYPE html> <html> <head> <title>TUT</title> </head> <body> {% for fm in stu_form %} <form method="post"> {%csrf_token%} {{fm.errors}}<br> {{fm.label}}:{{fm}}<br> {%endfor%} <button type="submit">Submit</button> </form> </body> </html> In delete_view.html − <!DOCTYPE html> <html> <head> <title>TUT</title> </head> <body> <form method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Confirm"> </form> </body> </html> In success.html − <!DOCTYPE html> <html> <head> <title>TUT</title> </head> <body> <h2>Success</h2> </body> </html> All the three are HTML files that we are rendering. home.html is for adding student, delete_view.html is for deleting student, and success.html for redirecting. Now you can proceed to check the output. Home.html − If you go to http://127.0.0.1:8000/student/delete/(student object id)/, then you will see our delete_view.html. Delete_view.html −
[ { "code": null, "e": 1292, "s": 1062, "text": "DeleteView is a view in Django which is used to delete any model data from the frontend. It is a built-in view that can be easily applied. It acts like admin page in deleting the view. It is really helpful in real-world projects." }, { "code": null, "e": 1435, "s": 1292, "text": "First of all, create a Django project and an app. I created the project with the name \"tutorial11\" and the app with the name \"modelFormsDemo\"." }, { "code": null, "e": 1497, "s": 1435, "text": "Now, let's do some basic things. Add the app in settings.py −" }, { "code": null, "e": 1534, "s": 1497, "text": "INSTALLED_APPS+ = ['modelFormsDemo']" }, { "code": null, "e": 1557, "s": 1534, "text": "In project's urls.py −" }, { "code": null, "e": 1726, "s": 1557, "text": "from django.contrib import admin\nfrom django.urls import path,include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('modelFormsDemo.urls'))\n]" }, { "code": null, "e": 1758, "s": 1726, "text": "Here we included the app's url." }, { "code": null, "e": 1777, "s": 1758, "text": "In app's urls.py −" }, { "code": null, "e": 2018, "s": 1777, "text": "from django.urls import path,include\nfrom . import views\n\nurlpatterns = [\n path('', views.home,name=\"home\"),\n path('student/delete//', views.StudentDeleteView.\nas_view(),name=\"delete\"),\n path('success/',views.success,name='success')\n]" }, { "code": null, "e": 2143, "s": 2018, "text": "Here we created 3 URLs: one for rendering the frontend, DeleteView for deleting, and Success for redirecting after deleting." }, { "code": null, "e": 2168, "s": 2143, "text": "In models.py, add this −" }, { "code": null, "e": 2384, "s": 2168, "text": "from django.db import models\n\n# Create your models here.\nclass Student(models.Model):\n name=models.CharField(max_length=100)\n standard=models.CharField(max_length=100)\n section=models.CharField(max_length=100)" }, { "code": null, "e": 2416, "s": 2384, "text": "Here we created a simple model." }, { "code": null, "e": 2449, "s": 2416, "text": "In views.py, add the following −" }, { "code": null, "e": 3003, "s": 2449, "text": "from django.shortcuts import render\nfrom .forms import StudentForm\nfrom django.views.generic.edit import DeleteView\nfrom .models import Student\nfrom django.urls import reverse_lazy\n\n# Create your views here.\ndef home(request):\n if request.method=='POST':\n form=StudentForm(request.POST)\n if form.is_valid():\n form.save()\n stuForm=StudentForm()\n return render(request,'home.html',{\"stu_form\":stuForm})\nclass StudentDeleteView(DeleteView):\n model=Student\n template_name='delete_view.html'\n success_url=reverse_lazy(\"success\")" }, { "code": null, "e": 3140, "s": 3003, "text": "Here, in home view, we rendered the frontend and in DeleteView, we rendered the delete_view.html which will ask for delete confirmation." }, { "code": null, "e": 3190, "s": 3140, "text": "Create forms.py in app directory and write this −" }, { "code": null, "e": 3360, "s": 3190, "text": "from django import forms\nfrom .models import Student\n\nclass StudentForm(forms.ModelForm):\n class Meta:\n model=Student\n fields=['name', 'standard', 'section']" }, { "code": null, "e": 3427, "s": 3360, "text": "Here we created our simple form which we will render in home view." }, { "code": null, "e": 3533, "s": 3427, "text": "Now create a templates folder and add three files inside it home.html, delete_view.html and success.html." }, { "code": null, "e": 3548, "s": 3533, "text": "In home.html −" }, { "code": null, "e": 3866, "s": 3548, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>TUT</title>\n </head>\n <body>\n {% for fm in stu_form %}\n <form method=\"post\">\n {%csrf_token%}\n {{fm.errors}}<br>\n {{fm.label}}:{{fm}}<br>\n {%endfor%}\n <button type=\"submit\">Submit</button>\n </form>\n </body>\n</html>" }, { "code": null, "e": 3888, "s": 3866, "text": "In delete_view.html −" }, { "code": null, "e": 4154, "s": 3888, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>TUT</title>\n </head>\n <body>\n <form method=\"post\">{% csrf_token %}\n <p>Are you sure you want to delete \"{{ object }}\"?</p>\n <input type=\"submit\" value=\"Confirm\">\n </form>\n </body>\n</html>" }, { "code": null, "e": 4172, "s": 4154, "text": "In success.html −" }, { "code": null, "e": 4293, "s": 4172, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>TUT</title>\n </head>\n <body>\n <h2>Success</h2>\n </body>\n</html>" }, { "code": null, "e": 4454, "s": 4293, "text": "All the three are HTML files that we are rendering. home.html is for adding student, delete_view.html is for deleting student, and success.html for redirecting." }, { "code": null, "e": 4495, "s": 4454, "text": "Now you can proceed to check the output." }, { "code": null, "e": 4507, "s": 4495, "text": "Home.html −" }, { "code": null, "e": 4619, "s": 4507, "text": "If you go to http://127.0.0.1:8000/student/delete/(student object id)/, then you will see our delete_view.html." }, { "code": null, "e": 4638, "s": 4619, "text": "Delete_view.html −" } ]
Protractor - Quick Guide
This chapter gives you an introduction to Protractor, where you will learn about the origin of this testing framework and why you have to choose this, working and limitations of this tool. Protractor is an open source end-to-end testing framework for Angular and AngularJS applications. It was built by Google on the top of WebDriver. It also serves as a replacement for the existing AngularJS E2E testing framework called “Angular Scenario Runner”. It also works as a solution integrator that combines powerful technologies such as NodeJS, Selenium, Jasmine, WebDriver, Cucumber, Mocha etc. Along with testing of AngularJS application, it also writes automated regression tests for normal web applications. It allows us to test our application just like a real user because it runs the test using an actual browser. The following diagram will give a brief overview of Protractor − Observe that in the above diagram, we have − Protractor − As discussed earlier, it is a wrapper over WebDriver JS especially designed for angular apps. Protractor − As discussed earlier, it is a wrapper over WebDriver JS especially designed for angular apps. Jasmine − It is basically a behavior-driven development framework for testing the JavaScript code. We can write the tests easily with Jasmine. Jasmine − It is basically a behavior-driven development framework for testing the JavaScript code. We can write the tests easily with Jasmine. WebDriver JS − It is a Node JS bindings implementation for selenium 2.0/WebDriver. WebDriver JS − It is a Node JS bindings implementation for selenium 2.0/WebDriver. Selenium − It simply automates the browser. Selenium − It simply automates the browser. As said earlier, Protractor is a replacement for the existing AngularJS E2E testing framework called “Angular Scenario Runner”. Basically, the origin of Protractor starts with the end of Scenario Runner. A question that arises here is why do we need to build Protractor? To understand this, we first need to check about its predecessor - Scenario Runner. Julie Ralph, the prime contributor to the development of Protractor, had the following experience with Angular Scenario Runner on other project within Google. This further became the motivation to build Protractor, specially to fill the gaps − “We tried using Scenario Runner and we found that it really just couldn’t do the things that we needed to test. We needed to test things like logging in. Your login page is not an Angular page, and the Scenario Runner couldn’t deal with that. And it couldn’t deal with things like popups and multiple windows, navigating the browser history, stuff like that.” The biggest advantage to the Protractor was the maturity of Selenium project and it wraps up its methods so that it can be easily used for Angular projects. The design of Protractor is built in such a way that it tests all layers such that web UI, backend services, persistence layer and so on of an application. As we know that almost all the applications are using JavaScript for development. The task of testers becomes difficult when JavaScript increases in size and becomes complex for applications due to the increasing number of the applications itself. Most of the times it becomes very difficult to capture the web elements in AngularJS applications, uses extended HTML syntax to express web application components, by using JUnit or Selenium WebDriver. The question here is that why Selenium Web Driver is not able to find AngularJS web elements? The reason is because AngularJS applications are having some extended HTML attributes like ng-repeater, ng-controller and ng-model etc. which are not included in Selenium locators. Here, the importance of Protractor comes into existence because Protractor on the top of Selenium can handle and control those extended HTML elements in AngularJS web applications. That is why we can say that most of the frameworks focus on conducting unit tests for AngularJS applications, Protractor used to do testing of the actual functionality of an application. Protractor, the testing framework, works in conjunction with Selenium to provide an automated test infrastructure for simulating a user’s interaction with an AngularJS application that is running in browser or mobile device. The working of Protractor can be understood with the help of following steps − Step 1 − In the first step, we need to write the tests. It can be done with the help of Jasmine or Mocha or Cucumber. Step 1 − In the first step, we need to write the tests. It can be done with the help of Jasmine or Mocha or Cucumber. Step 2 − Now, we need to run the test which can be done with the help of Protractor. It is also called test runner. Step 2 − Now, we need to run the test which can be done with the help of Protractor. It is also called test runner. Step 3 − In this step, Selenium server will help to manage the browsers. Step 3 − In this step, Selenium server will help to manage the browsers. Step 4 − At last, the browser APIs are invoked with the help of Selenium WebDriver. Step 4 − At last, the browser APIs are invoked with the help of Selenium WebDriver. This open source end-to-end testing framework offers the following advantages − An open source tool, Protractor is very easy to install and setup. An open source tool, Protractor is very easy to install and setup. Works well with Jasmine framework to create the test. Works well with Jasmine framework to create the test. Supports test driven development (TDD). Supports test driven development (TDD). Contains automatic waits which means we do not need to explicitly add waits and sleeps to our test. Contains automatic waits which means we do not need to explicitly add waits and sleeps to our test. Offers all the advantages of Selenium WebDriver. Offers all the advantages of Selenium WebDriver. Supports parallel testing through multiple browsers. Supports parallel testing through multiple browsers. Provides the benefit of auto-synchronization. Provides the benefit of auto-synchronization. Has excellent testing speed. Has excellent testing speed. This open source end-to-end testing framework possesses the following limitations − Does not uncover any verticals in browser automation because it is a wrapper for WebDriver JS. Does not uncover any verticals in browser automation because it is a wrapper for WebDriver JS. Knowledge of JavaScript is essential for the user, because it is available only for JavaScript. Knowledge of JavaScript is essential for the user, because it is available only for JavaScript. Only provides front-end testing because it is a UI driven testing tool. Only provides front-end testing because it is a UI driven testing tool. Since the knowledge of JavaScript is essential for working with Protractor, in this chapter, let us understand the concepts of JavaScript testing in detail. JavaScript is the most popular dynamically typed and interpreted scripting language, but the most challenging task is to test the code. It is because, unlike other compiled languages like JAVA, and C++, there are no compilation steps in JavaScript that can help the tester to figure out errors. Besides, browser-based testing is very time consuming; hence there is a necessity for tools that support automated testing for JavaScript. It is always a good practice to write the test because it makes the code better; the issue with manual testing is that it is a bit time consuming and error prone. The process of manual testing is quite boring for programmer too as they need to repeat the process, writing test specs, change the code and refresh the browser several times. Besides, manual testing also slows down the development process. Due to the above reasons, it is always useful to have some tools that can automate these tests and help programmers to get rid of these repetitive and boring steps. What should a developer do to make the testing process automated? Basically, a developer can implement the tool set in the CLI (Command Line Interpreter) or in the development IDE (Integrated development environment). Then, these tests will run continuously in a separate process even without the input from the developer. Automated testing of JavaScript is also not new and lots of tools like Karma, Protractor, CasperJS etc. have been developed. There can be different tests for different purposes. For example, some tests are written to check the behavior of functions in a program, while some other are written to test the flow of a module or feature. Thus, we have the following two types of testing − The testing is done on the smallest testable part of the program called unit. The unit is basically tested in isolation without any kind of dependency of that unit on the other parts. In case of JavaScript, the individual method or function having a specific behavior can be a unit of code and these units of code must be tested in an isolated way. One of the advantages of unit testing is that the testing of units can be done in any order because the units are independent of each other. Another advantage of unit testing which really counts is that it can run the test at any time as follows − From the very beginning of the development process. After completing the development of any module/feature. After modifying any module/feature. After adding any new feature in the existing application. For automated unit testing of JavaScript applications, we can choose from many testing tools and frameworks such as Mocha, Jasmine and QUnit. It may be defined as the testing methodology used to test whether the flow of the application from start to finish (from one end to another end) is working fine as per design. End-to-end testing is also called function/flow testing. Unlike unit testing, end-to-end testing tests how individual components work together as an application. This is the main difference between unit testing and end-to-end testing. For example, suppose if we have a registration module where the user needs to provide some valid information to complete the registration then the E2E testing for that particular module will follow following steps to complete the testing − First, it will load/compile the form or module. Now, it will get the DOM (Document object model) of the form’s elements. Next, trigger the click event of the submit button for checking if it is working or not. Now, for validation purpose collect the value from the input fields. Next, the input fields should be validated. For testing purpose, call a fake API to store the data. Every step gives its own results which will be compared with the expected result set. Now, the question that arises is, while this kind of E2E or functional testing can be performed manually also, why we need automation for this? The main reason is that automation will make this test process easy. Some of the available tools that can be easily integrate with any application, for this purpose are Selenium, PhantomJS and Protractor. We have various testing tools and frameworks for Angular testing. The following are some of the well-known tools and frameworks − Karma, created by Vojta Jina, is a test runner. Originally this project was called Testacular. It is not a test framework, which means that it gives us the ability to easily and automatically run JavaScript unit tests on real browsers. Karma was built for AngularJS because before Karma there was no automated testing tool for web-based JavaScript developers. On the other hand, with the automation provided by Karma, developers can run a simple single command and determine whether an entire test suite has passed or failed. The following are some pros of using Karma in comparison to the manual process − Automates tests in multiple browsers as well as devices. Monitors files for errors and fixes them. Provides online support and documentation. Eases the integration with a continuous integration server. The followings are some cons of using Karma − The main disadvantage of using Karma is that it requires an additional tool to configure and maintain. If you are using Karma test runner with Jasmine, then less documentation is available for finding information about setting up your CSS in the case of having multiple ids for one element. Jasmine, a behavior-driven development framework for testing JavaScript code, is developed at Pivotal Labs. Before the active development of Jasmine framework, a similar unit testing framework named JsUnit was also developed by Pivotal Labs, which has an inbuilt test runner. The browsers tests can be run through Jasmine tests by including SpecRunner.html file or by using it as a command line test runner also. It can be used with or without Karma also. The followings are some pros of using Jasmine − A framework independent of browser, platform and language. A framework independent of browser, platform and language. Supports test driven development (TDD) along with behavioral driven development. Supports test driven development (TDD) along with behavioral driven development. Has default integration with Karma. Has default integration with Karma. Easy to understand syntax. Easy to understand syntax. Provides test spies, fakes and pass-through functionalities which assist with testing as additional functions. Provides test spies, fakes and pass-through functionalities which assist with testing as additional functions. The following is a con of using Jasmine − The tests must be return by the user as they change because there is no file-watching feature available in Jasmine while running test. The tests must be return by the user as they change because there is no file-watching feature available in Jasmine while running test. Mocha, written for Node.js applications, is a testing framework but it also supports browser testing. It is quite like Jasmine but the major difference between them is that Mocha needs some plugin and library because it cannot run standalone as a test framework. On the other hand, Jasmine is standalone. However, Mocha is more flexible to use than Jasmine. The following are some pros of using Mocha − Mocha is very easy to install and configure. User-friendly and simple documentation. Contains plugins with several node projects. The following are some cons of using Mocha − It needs separate modules for assertions, spies etc. It also requires additional configuration for using with Karma. QUint, originally developed by John Resig in 2008 as part of jQuery, is a powerful yet easy-to-use JavaScript unit test suite. It can be used to test any generic JavaScript code. Although it focuses on testing JavaScript in the browser, yet it is very convenient to use by the developer. The following are some pros of using QUnit − Easy to install and configure. User-friendly and simple documentation. The following is a con of using QUnit − It was mainly developed for jQuery and hence not so good for use with other frameworks. Selenium, originally developed by Jason Huggins in 2004 as an internal tool at ThoughtWorks, is an open source testing automation tool. Selenium defines itself as “Selenium automates browsers. That’s it!”. Automation of browsers means that the developers can interact with the browsers very easily. The following are some pros of using Selenium − Contains large feature set. Supports distributed testing. Has SaaS support through services such as Sauce Labs. Easy to use with simple documentations and rich resources available. The followings are some cons of using Selenium − A main disadvantage of using Selenium is that it must be run as a separate process. Configuration is a bit cumbersome as the developer needs to follow several steps. In the previous chapters, we have learnt the basics of Protractor. In this chapter, let us learn how to install and configure it. We need to satisfy the following prerequisites before installing Protractor on your computer − Protractor is a Node.js module, hence the very important prerequisite is that we must have Node.js installed on our computer. We are going to install Protractor package using npm (a JavaScript package manager), that comes with Node.js. For installing Node.js please follow the official link − https://nodejs.org/en/download/. After installing Node.js, you can check the version of Node.js and npm by writing the command node --version and npm --version in the command prompt as shown below − Google Chrome, a web browser built by Google, will be used to run end-to-end tests in Protractor without the need for a Selenium server. You can download chrome by clicking on the link − https://www.google.com/chrome/. This tool is provided with the Protractor npm module and allows us to interact with web applications. After installing Node.js on our computer, we can install Protractor with the help of following command − npm install -g protractor Once protractor is successfully installed, we can check its version by writing protractor --version command in the command prompt as shown below − After installing Protractor, we need to install Selenium WebDriver for Chrome. It can be installed with the help of following command − webdriver-manager update The above command will create a Selenium directory which contains the required Chrome driver used in the project. We can confirm the installation and configurati on of Protractor by doing a slightly changing the conf.js provided in the example after installing Protractor. You can find this conf.js file in the root directory node_modules/Protractor/example. For this, first create a new file named testingconfig.js in the same directory i.e. node_modules/Protractor/example. Now, in the conf.js file, under the source file declaration parameter, write testingconfig.js. Next, save and close all the files and open command prompt. Run the conf.js file as shown in the screenshot given below. The configuration and installation of Protractor is successful if you got the output as shown below − The above output shows that there is no specification because we provided the empty file at source file declaration parameter in conf.js file. But from the above output, we can see that both protractor and WebDriver are running successfully. While installing and configuring Protractor and WebDriver, we might come across the following common issues − It is the most common issue while installing WebDriver. This issue arises if you do not update the WebDriver. Note that we must update WebDriver, otherwise we would not be able to reference it to Protractor installation. Another common issue is that after running Protractor, it shows that unable to find tests. For this,we must have to ensure that the relative paths, filenames or extensions are correct. We also need to write conf.js file very carefully because it starts with configuration file itself. As discussed earlier, Protractor is an open source, end-to-end testing framework for Angular and AngularJS applications. It is Node.js program. On the other hand, Selenium is a browser automation framework that includes the Selenium Server, the WebDriver APIs and the WebDriver browser drivers. If we talk about the conjunction of Protractor and Selenium, Protractor can work with Selenium server to provide an automated test infrastructure. The infrastructure can simulate user’s interaction with an angular application that is running in a browser or on mobile device. The conjunction of Protractor and Selenium can be divided into three partitions namely test, server and Browser, as shown in the following diagram − As we have seen in the above diagram, a test using Selenium WebDriver involves the following three processes − The test scripts The server The browser In this section, let us discuss the communication between these three processes. The communication between the first two processes - the test scripts and the server depends upon the working of Selenium Server. In other words, we can say that the way Selenium server is running will give the shape to the communication process between test scripts and server. Selenium server can run locally on our machine as standalone Selenium Server (selenium-server-standalone.jar) or it can run remotely via a service (Sauce Labs). In case of standalone Selenium server, there would be an http communication between Node.js and selenium server. As we know that the server is responsible for forwarding commands to the browser after interpreting the same from the test scripts. That is why server and the browser also require a communication medium and here the communication is done with the help of JSON WebDriver Wire Protocol. The browser extended with Browser Driver that is used to interpret the commands. The above concept about Selenium WebDriver processes and their communication can be understood with the help of following diagram − While working with Protractor, the very first process, that is test script is run using Node.js but before performing any action on the browser it will send an extra command to make it sure that the application being tested is stabilized. Selenium Server acts like a proxy server in between our test script and the browser driver. It basically forwards the command from our test script to the WebDriver and returns the responses from the WebDriver to our test script. There are following options for setting up the Selenium server which are included in conf.js file of test script − If we want to run the server on our local machine, we need to install standalone selenium server. The prerequisite to install standalone selenium server is JDK (Java Development Kit). We must have JDK installed on our local machine. We can check it by running the following command from command line − java -version Now, we have the option to install and start Selenium Server manually or from test script. For installing and starting Selenium server manually, we need to use WebDriver-Manager command line tool that comes with Protractor. The steps for installing and starting Selenium server are as follows − Step 1 − The first step is to install the Selenium server and ChromeDriver. It can be done with the help of running following command − webdriver-manager update Step 2 − Next, we need to start the server. It can be done with the help of running following command − webdriver-manager start Step 3 − At last we need to set seleniumAddress in config file to the address of the running server. The default address would be http://localhost:4444/wd/hub. For starting Selenium server from a Test Script, we need to set the following options in our config file − Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar. Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar. Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444. Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444. Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag. Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag. Another option for running our test is to use Selenium server remotely. The prerequisite for using server remotely is that we must have an account with a service that hosts the server. While working with Protractor we have the built-in support for the following services hosting the server − For using TestObject as the remote Selenium Server, we need to set the testobjectUser, the user name of our TestObject account and testobjectKey, the API key of our TestObject account. For using BrowserStack as the remote Selenium Server, we need to set the browserstackUser, the user name of our BrowserStack account and browserstackKey, the API key of our BrowserStack account. For using Sauce Labs as the remote Selenium Server, we need to set the sauceUser, the user name of our Sauce Labs account and SauceKey, the API key of our Sauce Labs account. For using Kobiton as the remote Selenium Server we need to set the kobitonUser, the user name of our Kobiton account and kobitonKey, the API key of our Kobiton account. One more option for running our test is to connect to the Browser Driver directly without using Selenium server. Protractor can test directly, without the use of Selenium Server, against Chrome and Firefox by setting directConnect: true in config file. Before configuring and setting up the browser, we need to know which browsers are supported by Protractor. The following is the list of browsers supported by Protractor − ChromeDriver FirefoxDriver SafariDriver IEDriver Appium-iOS/Safari Appium-Android/Chrome Selendroid PhantomJS For setting and configuring the browser, we need to move to config file of Protractor because the browser setup is done within the capabilities object of config file. For setting up the Chrome Browser, we need to set the capabilities object as follows capabilities: { 'browserName': 'chrome' } We can also add Chrome-Specific options which are nested in the chromeOptions and its full list can be seen at https://sites.google.com/a/chromium.org/chromedriver/capabilities. For example, if you want to add FPS-counter in the upper right, then it can be done as follows in the config file − capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, For setting up the Firefox browser, we need to set the capabilities object as follows − capabilities: { 'browserName': 'firefox' } We can also add Firefox-Specific options which are nested in the moz:firefoxOptions object and its full list can be seen at https://github.com/mozilla/geckodriver#firefox-capabilities. For example, if you want to run your test on Firefox in safe mode then it can be done as follows in the config file − capabilities: { 'browserName': 'firefox', 'moz:firefoxOptions': { 'args': ['—safe-mode'] } }, For setting up any other browser than Chrome or Firefox, we need to install a separate binary from https://docs.seleniumhq.org/download/. Actually, PhantomJS is no longer supported because of its crashing issues. Instead of that it is recommended to use headless Chrome or headless Firefox. They can be set up as follows − For setting up headless Chrome, we need to start Chrome with the –headless flag as follows − capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': [“--headless”, “--disable-gpu”, “--window-size=800,600”] } }, For setting up headless Firefox, we need to start Firefox with the –headless flag as follows − capabilities: { 'browserName': 'firefox', 'moz:firefoxOptions': { 'args': [“--headless”] } }, We can also test against multiple browsers. For this we need to use multiCapabilities configuration option as follows − multiCapabilities: [{ 'browserName': 'chrome' },{ 'browserName': 'firefox' }] Two BDD (Behavior driven development) test frameworks, Jasmine and Mocha are supported by Protractor. Both frameworks are based on JavaScript and Node.js. The syntax, report and scaffolding, required for writing and managing the tests, are provided by these frameworks. Next, we see how we can install various frameworks − It is the default test framework for Protractor. When you install Protractor, you will get Jasmine 2.x version with it. We do not need to get it installed separately. Mocha is another JavaScript test framework basically running on Node.js. For using Mocha as our test framework, we need to use the BDD (Behavior driven development) interface and Chai assertions with Chai As Promised. The installation can be done with the help of following commands − npm install -g mocha npm install chai npm install chai-as-promised As you can see, -g option is used while installing mocha, it is because we have installed Protractor globally using the -g option. After installing it, we need to require and set up Chai inside our test files. It can be done as follows − var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; After this, we can use Chai As Promised as such − expect(myElement.getText()).to.eventually.equal('some text'); Now, we need to set the framework property to mocha of config file by adding framework: ‘mocha’. The options like ‘reporter’ and ‘slow’ for mocha can be added in config file as follows − mochaOpts: { reporter: "spec", slow: 3000 } For using Cucumber as our test framework, we need to integrate it with Protractor with framework option custom. The installation can be done with the help of following commands npm install -g cucumber npm install --save-dev protractor-cucumber-framework As you can see, -g option is used while installing Cucumber, it is because we have installed Protractor globally i.e. with -g option. Next, we need to set the framework property to custom of config file by adding framework: ‘custom’ and frameworkPath: ‘Protractor-cucumber-framework’ to the config file named cucumberConf.js. The sample code shown below is a basic cucumberConf.js file which can be used to run cucumber feature files with Protractor − exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', baseUrl: 'https://angularjs.org/', capabilities: { browserName:'Firefox' }, framework: 'custom', frameworkPath: require.resolve('protractor-cucumber-framework'), specs: [ './cucumber/*.feature' ], // cucumber command line options cucumberOpts: { require: ['./cucumber/*.js'], tags: [], strict: true, format: ["pretty"], 'dry-run': false, compiler: [] }, onPrepare: function () { browser.manage().window().maximize(); } }; In this chapter, let us understand how to write the first test in Protractor. Protractor needs the following two files to run − It is one of the important files to run Protractor. In this file, we will write our actual test code. The test code is written by using the syntax of our testing framework. For example, if we are using Jasmine framework, then the test code will be written by using the syntax of Jasmine. This file will contain all the functional flows and assertions of the test. In simple words, we can say that this file contains the logic and locators to interact with the application. The following is a simple script, TestSpecification.js, having the test case to navigate to an URL and check for the page title − //TestSpecification.js describe('Protractor Demo', function() { it('to check the page title', function() { browser.ignoreSynchronization = true; browser.get('https://www.tutorialspoint.com/tutorialslibrary.htm'); browser.driver.getTitle().then(function(pageTitle) { expect(pageTitle).toEqual('Free Online Tutorials and Courses'); }); }); }); The code of above specification file can be explained as follows − It is the global variable created by Protractor to handle all the browser level commands. It is basically a wrapper around an instance of WebDriver. browser.get() is a simple Selenium method that will tell Protractor to load a particular page. describe and it − Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas ‘it’ contains some of the test scenarios. We can have multiple ‘it’ blocks in our test case program. describe and it − Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas ‘it’ contains some of the test scenarios. We can have multiple ‘it’ blocks in our test case program. Expect − It is an assertion where we are comparing the web page title with some predefined data. Expect − It is an assertion where we are comparing the web page title with some predefined data. ignoreSynchronization − It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to “true”. ignoreSynchronization − It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to “true”. As the name suggests, this file provides explanations for all the Protractor configuration options. It basically tells Protractor the following − Where to find the test or specs files Which browser to pick Which testing framework to use Where to talk with the Selenium Server The following is the simple script, config.js, having the test // config.js exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. specs: ['TestSpecification.js'], The code of above configuration file having three basic parameters, can be explained as follows − This parameter is used to specify the name of the browser. It can be seen in the following code block of conf.js file − exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, As seen above, the name of the browser given here is ‘chrome’ which is by default browser for Protractor. We can also change the name of the browser. This parameter is used to specify the name of the testing framework. It can be seen in the following code block of config.js file − exports.config = { directConnect: true, // Framework to use. Jasmine is recommended. framework: 'jasmine', Here we are using ‘jasmine’ test framework. This parameter is used to specify the name of the source file declaration. It can be seen in the following code block of conf.js file − exports.config = { directConnect: true, // Spec patterns are relative to the current working directory when protractor is called. specs: ['TsetSpecification.js'], As seen above, the name of the source file declaration given here is ‘TestSpecification.js’. It is because, for this example we have created the specification file with name TestSpecification.js. As we have got basic understanding about the necessary files and their coding for running Protractor, let us try to run the example. We can follow the following steps to execute this example − Step 1 − First, open command prompt. Step 1 − First, open command prompt. Step 2 − Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js. Step 2 − Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js. Step 3 − Now, execute the config.js file by running the command Protrcator config.js. Step 3 − Now, execute the config.js file by running the command Protrcator config.js. The screen shot shown below will explain the above steps for executing the example − It is seen in the screen shot that the test has been passed. Now, suppose if we are testing non-angular websites and not putting the ignoreSynchronization tag to true then after executing the code we will get the error” Angular could not be found on the page”. It can be seen in the following screen shot − Till now, we have discussed about the necessary files and their coding for running test cases. Protractor is also able to generate the report for test cases. For this purpose, it supports Jasmine. JunitXMLReporter can be used to generate test execution reports automatically. But before that, we need to install Jasmine reporter with the help of following command − npm install -g jasmine-reporters As you can see, -g option is used while installing Jasmine Reporters, it is because we have installed Protractor globally, with -g option. After successfully installing jasmine-reporters, we need to add the following code into our previously used config.js file − onPrepare: function(){ //configure junit xml report var jasmineReporters = require('jasmine-reporters'); jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, filePrefix: 'guitest-xmloutput', savePath: 'test/reports' })); Now, our new config.js file would be as follows − // An example configuration file. exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. specs: ['TestSpecification.js'], //framework: "jasmine2", //must set it if you use JUnitXmlReporter onPrepare: function(){ //configure junit xml report var jasmineReporters = require('jasmine-reporters'); jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({ consolidateAll: true, filePrefix: 'guitest-xmloutput', savePath: 'reports' })); }, }; After running the above config file in the same way, we have run previously, it will generate an XML file containing the report under the root directory in reports folder. If the test got successful, the report will look like below − But, if the test failed, the report will look as shown below − This chapter lets you understand various core APIs that are key to the functioning of protractor. Protractor provides us a wide range of APIs which are very important in order to perform the following actions for getting the current state of the website − Getting the DOM elements of the web page we are going to test. Interacting with the DOM elements. Assigning actions to them. Sharing information to them. To perform the above tasks, it is very important to understand Protractor APIs. As we know that Protractor is a wrapper around Selenium-WebDriver which is the WebDriver bindings for Node.js. Protractor has the following APIs − It is a wrapper around an instance of WebDriver which is used to handle browser level commands such as navigation, page-wide information etc. For example, the browser.get method loads a page. It is used to search and interact with DOM element on the page we are testing. For this purpose, it requires one parameter for locating the element. It is a collection of element locator strategies. The elements, for example, can be found by CSS selector, by ID or by any other attribute they are bound to with ng-model. Next, we are going to discuss in detail about these APIs and their functions. As discussed above, it is a wrapper around an instance of WebDriver for handling browser level commands. It performs various functions as follows − The functions of ProtractorBrowser API are as follows− browser.angularAppRoot This function of Browser API sets the CSS selector for an element on which we are going to find Angular. Usually, this function is in ‘body’, but in case if our ng-app, it is on a sub-section of the page; it may be a sub-element also. browser.waitForAngularEnabled This function of Browser API can be set to true or false. As the name suggests, if this function is set for false then Protractor will not wait for Angular $http and $timeout tasks to complete before interacting with the browser. We can also read the current state without changing it by calling waitForAngularEnabled() without passing a value. browser.getProcessedConfig With the help of this browser APIs function we can get the processed configuration object, including specification & capabilities, that is currently being run. browser.forkNewDriverInstance As the name suggests this function will fork another instance of browser to be used in interactive tests. It can be run with control flow enabled and disabled. Example is given below for both the cases − Example 1 Running browser.forkNewDriverInstance() with control flow enabled − var fork = browser.forkNewDriverInstance(); fork.get(‘page1’); Example 2 Running browser.forkNewDriverInstance() with control flow disabled − var fork = await browser.forkNewDriverInstance().ready; await forked.get(‘page1’); browser.restart As the name suggests, it will restart the browser by closing browser instance and creating new one. It can also run with control flow enabled and disabled. Example is given below for both the cases − Example 1 − Running browser.restart() with control flow enabled − browser.get(‘page1’); browser.restart(); browser.get(‘page2’); Example 2 − Running browser.forkNewDriverInstance() with control flow disabled − await browser.get(‘page1’); await browser.restart(); await browser.get(‘page2’); It is similar to browser.restart() function. The only difference is that it returns the new browser instance directly rather than returning a promise resolving to the new browser instance. It can only run when the control flow is enabled. Example − Running browser.restartSync() with control flow enabled − browser.get(‘page1’); browser.restartSync(); browser.get(‘page2’); browser.useAllAngular2AppRoots As the name suggests, it is compatible with Angular2 only. It will search through all the angular apps available on the page while finding elements or waiting for stability. browser.waitForAngular This browser API function instructs the WebDriver to wait until Angular has finished rendering and has no outstanding $http or $timeout calls before continuing. browser.findElement As the name suggests, this browser API function waits for Angular to finish rendering before searching for element. browser.isElementPresent As the name suggests, this browser API function will test for the for the element to be present on the page or not. browser.addMockModule It will add a module to load before Angular every time Protractor.get method is called. Example browser.addMockModule('modName', function() { angular.module('modName', []).value('foo', 'bar'); }); browser.clearMockModules unlike browser.addMockModule, it will clear the list of registered mock modules. browser.removeMockModule As the name suggests, it will remove a register mock modules. Example: browser.removeMockModule(‘modName’); browser.getRegisteredMockModules Opposite to browser.clearMockModule, it will get the list of registered mock modules. browser.get We can use browser.get() to navigate the browser to a particular web address and load the mock modules for that page before the Angular load. Example browser.get(url); browser.get('http://localhost:3000'); // This will navigate to the localhost:3000 and will load mock module if needed browser.refresh As the name suggests, this will reload the current page and loads mock modules before Angular. browser.navigate As the name suggests, it is used to mix navigation methods back into the navigation object so that they are invoked as before. Example: driver.navigate().refresh(). browser.setLocation It is use to browse to another page using in-page navigation. Example browser.get('url/ABC'); browser.setLocation('DEF'); expect(browser.getCurrentUrl()) .toBe('url/DEF'); It will navigate from ABC to DEF page. browser.debugger As the name suggests, this must be used with protractor debug. This function basically adds a task to the control flow to pause the test and inject helper functions into the browser so that debugging can be done in browser console. browser.pause It is used for debugging WebDriver tests. We can use browser.pause() in our test to enter the protractor debugger from that point in the control flow. Example element(by.id('foo')).click(); browser.pause(); // Execution will stop before the next click action. element(by.id('bar')).click(); browser.controlFlowEnabled It is used to determine whether the control flow is enabled or not. In this chapter, let us learn some more core APIs of Protractor. Element is one of the global functions exposed by protractor. This function takes a locater and returns the following − ElementFinder, that finds a single element based on the locator. ElementArrayFinder, that finds an array of elements based on the locator. Both the above support chaining methods as discussed below. The Followings are the functions of ElementArrayFinder − element.all(locator).clone As the name suggests, this function will create a shallow copy of the array of the elements i.e. ElementArrayFinder. element.all(locator).all(locator) This function basically returns a new ElementArrayFinder which could be empty or contain the children elements. It can be used for selecting multiple elements as an array as follows Example element.all(locator).all(locator) elementArr.all(by.css(‘.childselector’)); // it will return another ElementFindArray as child element based on child locator. element.all(locator).filter(filterFn) As the name suggests, after applying filter function to each element within ElementArrayFinder, it returns a new ElementArrayFinder with all elements that pass the filter function. It is basically having two arguments, first is ElementFinder and second is index. It can also be used in page objects. Example View <ul class = "items"> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> Code element.all(by.css('.items li')).filter(function(elem, index) { return elem.getText().then(function(text) { return text === 'Third'; }); }).first().click(); element.all(locator).get(index) With the help of this, we can get an element within the ElementArrayFinder by index. Note that the index starts at 0 and negative indices are wrapped. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let list = element.all(by.css('.items li')); expect(list.get(0).getText()).toBe('First'); expect(list.get(1).getText()).toBe('Second'); element.all(locator).first() As the name suggests, this will get the first element for ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let first = element.all(by.css('.items li')).first(); expect(first.getText()).toBe('First'); element.all(locator).last() As name suggest, this will get the last element for ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let first = element.all(by.css('.items li')).last(); expect(last.getText()).toBe('Third'); element.all(locator).all(selector) It is used to find an array of elements within a parent when calls to $$ may be chained. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).$$('li'); element.all(locator).count() As the name suggests, this will count the number of elements represented by ElementArrayFinder. It will not retrieve the underlying element. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let list = element.all(by.css('.items li')); expect(list.count()).toBe(3); element.all(locator).isPresent() It will match the elements with the finder. It can return true or false. True, if there are any elements present that match the finder and False otherwise. Example expect($('.item').isPresent()).toBeTruthy(); element.all(locator).locator As the name suggests, it will return the most relevant locator. Example $('#ID1').locator(); // returns by.css('#ID1') $('#ID1').$('#ID2').locator(); // returns by.css('#ID2') $$('#ID1').filter(filterFn).get(0).click().locator(); // returns by.css('#ID1') element.all(locator).then(thenFunction) It will retrieve the elements represented by the ElementArrayFinder. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code element.all(by.css('.items li')).then(function(arr) { expect(arr.length).toEqual(3); }); element.all(locator).each(eachFunction) As the name suggests, it will call the input function on each ElementFinder represented by the ElementArrayFinder. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code element.all(by.css('.items li')).each(function(element, index) { // It will print First 0, Second 1 and Third 2. element.getText().then(function (text) { console.log(index, text); }); }); element.all(locator).map(mapFunction) As name suggest, it will apply a map function on each element within the ElementArrayFinder. It is having two arguments. First would be the ElementFinder and second would be the index. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let items = element.all(by.css('.items li')).map(function(elm, index) { return { index: index, text: elm.getText(), class: elm.getAttribute('class') }; }); expect(items).toEqual([ {index: 0, text: 'First', class: 'one'}, {index: 1, text: 'Second', class: 'two'}, {index: 2, text: 'Third', class: 'three'} ]); element.all(locator).reduce(reduceFn) As the name suggests, it will apply a reduce function against an accumulator and every element found using the locator. This function will reduce every element into a single value. Example View <ul class = "items"> <li>First</li> <li>Second</li> <li>Third</li> </ul> Code let value = element.all(by.css('.items li')).reduce(function(acc, elem) { return elem.getText().then(function(text) { return acc + text + ' '; }); }, ''); expect(value).toEqual('First Second Third '); element.all(locator).evaluate As the name suggests, it will evaluate the input whether it is in the scope of the current underlying elements or not. Example View <span class = "foo">{{letiableInScope}}</span> Code let value = element.all(by.css('.foo')).evaluate('letiableInScope'); element.all(locator).allowAnimations As name suggest, it will determine whether the animation is allowed on the current underlying elements or not. Example element(by.css('body')).allowAnimations(false); Chaining functions of ElementFinder and their descriptions − element(locator).clone As the name suggests, this function will create a shallow copy of the ElementFinder. element(locator).getWebElement() It will return the WebElement represented by this ElementFinder and a WebDriver error will be thrown if the element does not exist. Example View <div class="parent"> some text </div> Code // All the four following expressions are equivalent. $('.parent').getWebElement(); element(by.css('.parent')).getWebElement(); browser.driver.findElement(by.css('.parent')); browser.findElement(by.css('.parent')); element(locator).all(locator) It will find an array of elements within a parent. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).all(by.tagName('li')); element(locator).element(locator) It will find elements within a parent. Example View <div class = "parent"> <div class = "child"> Child text <div>{{person.phone}}</div> </div> </div> Code // Calls Chain 2 element. let child = element(by.css('.parent')). element(by.css('.child')); expect(child.getText()).toBe('Child text\n981-000-568'); // Calls Chain 3 element. let triple = element(by.css('.parent')). element(by.css('.child')). element(by.binding('person.phone')); expect(triple.getText()).toBe('981-000-568'); element(locator).all(selector) It will find an array of elements within a parent when calls to $$ may be chained. Example View <div class = "parent"> <ul> <li class = "one">First</li> <li class = "two">Second</li> <li class = "three">Third</li> </ul> </div> Code let items = element(by.css('.parent')).$$('li')); element(locator).$(locator) It will find elements within a parent when calls to $ may be chained. Example View <div class = "parent"> <div class = "child"> Child text <div>{{person.phone}}</div> </div> </div> Code // Calls Chain 2 element. let child = element(by.css('.parent')). $('.child')); expect(child.getText()).toBe('Child text\n981-000-568'); // Calls Chain 3 element. let triple = element(by.css('.parent')). $('.child')). element(by.binding('person.phone')); expect(triple.getText()).toBe('981-000-568'); element(locator).isPresent() It will determine whether the element is presented on page or not. Example View <span>{{person.name}}</span> Code expect(element(by.binding('person.name')).isPresent()).toBe(true); // will check for the existence of element expect(element(by.binding('notPresent')).isPresent()).toBe(false); // will check for the non-existence of element element(locator).isElementPresent() It is same as element(locator).isPresent(). The only difference is that it will check whether the element identified by sublocator is present rather than the current element finder. element.all(locator).evaluate As the name suggests, it will evaluate the input whether it is on the scope of the current underlying elements or not. Example View <span id = "foo">{{letiableInScope}}</span> Code let value = element(by.id('.foo')).evaluate('letiableInScope'); element(locator).allowAnimations As the name suggests, it will determine whether the animation is allowed on the current underlying elements or not. Example element(by.css('body')).allowAnimations(false); element(locator).equals As the name suggests, it will compare an element for equality. It is basically a collection of element locator strategies that provides ways of finding elements in Angular applications by binding, model etc. Functions and their descriptions The functions of ProtractorLocators API are as follows − by.addLocator(locatorName,fuctionOrScript) It will add a locator to this instance of ProtrcatorBy which further can be used with element(by.locatorName(args)). Example View <button ng-click = "doAddition()">Go!</button> Code // Adding the custom locator. by.addLocator('buttonTextSimple', function(buttonText, opt_parentElement, opt_rootSelector) { var using = opt_parentElement || document, buttons = using.querySelectorAll('button'); return Array.prototype.filter.call(buttons, function(button) { return button.textContent === buttonText; }); }); element(by.buttonTextSimple('Go!')).click();// Using the custom locator. by.binding As the name suggests, it will find an element by text binding. A partial match will be done so that any elements bound to the variables containing the input string will be returned. Example View <span>{{person.name}}</span> <span ng-bind = "person.email"></span> Code var span1 = element(by.binding('person.name')); expect(span1.getText()).toBe('Foo'); var span2 = element(by.binding('person.email')); expect(span2.getText()).toBe('[email protected]'); by.exactbinding As the name suggests, it will find an element by exact binding. Example View <spangt;{{ person.name }}</spangt; <span ng-bind = "person-email"gt;</spangt; <spangt;{{person_phone|uppercase}}</span> Code expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); expect(element(by.exactBinding('person')).isPresent()).toBe(false); expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); expect(element(by.exactBinding('phone')).isPresent()).toBe(false); by.model(modelName) As the name suggests, it will find an element by ng-model expression. Example View <input type = "text" ng-model = "person.name"> Code var input = element(by.model('person.name')); input.sendKeys('123'); expect(input.getAttribute('value')).toBe('Foo123'); by.buttonText As the name suggests, it will find a button by text. Example View <button>Save</button> Code element(by.buttonText('Save')); by.partialButtonText As the name suggests, it will find a button by partial text. Example View <button>Save my file</button> Code element(by.partialButtonText('Save')); by.repeater As the name suggests, it will find an element inside an ng-repeat. Example View <div ng-repeat = "cat in pets"> <span>{{cat.name}}</span> <span>{{cat.age}}</span> <</div> <div class = "book-img" ng-repeat-start="book in library"> <span>{{$index}}</span> </div> <div class = "book-info" ng-repeat-end> <h4>{{book.name}}</h4> <p>{{book.blurb}}</p> </div> Code var secondCat = element(by.repeater('cat in pets').row(1)); // It will return the DIV for the second cat. var firstCatName = element(by.repeater('cat in pets'). row(0).column('cat.name')); // It will return the SPAN for the first cat's name. by.exactRepeater As the name suggests, it will find an element by exact repeater. Example View <li ng-repeat = "person in peopleWithRedHair"></li> <li ng-repeat = "car in cars | orderBy:year"></li> Code expect(element(by.exactRepeater('person in peopleWithRedHair')).isPresent()) .toBe(true); expect(element(by.exactRepeater('person in people')).isPresent()).toBe(false); expect(element(by.exactRepeater('car in cars')).isPresent()).toBe(true); by.cssContainingText As name suggest, it will find the elements, containing exact string, by CSS Example View <ul> <li class = "pet">Dog</li> <li class = "pet">Cat</li> </ul> Code var dog = element(by.cssContainingText('.pet', 'Dog')); // It will return the li for the dog, but not for the cat. by.options(optionsDescriptor) As the name suggests, it will find an element by ng-options expression. Example View <select ng-model = "color" ng-options = "c for c in colors"> <option value = "0" selected = "selected">red</option> <option value = "1">green</option> </select> Code var allOptions = element.all(by.options('c for c in colors')); expect(allOptions.count()).toEqual(2); var firstOption = allOptions.first(); expect(firstOption.getText()).toEqual('red'); by.deepCSS(selector) As name suggest, it will find an element by CSS selector within the shadow DOM. Example View <div> <span id = "outerspan"> <"shadow tree"> <span id = "span1"></span> <"shadow tree"> <span id = "span2"></span> </> </> </div> Code var spans = element.all(by.deepCss('span')); expect(spans.count()).toEqual(3); This chapter discusses in detail about the objects in Protractor. Page object is a design pattern which has become popular for writing e2e tests in order to enhance the test maintenance and reducing the code duplication. It may be defined as an object-oriented class serving as an interface to a page of your AUT (application under test). But, before diving deep into page objects, we must have to understand the challenges with automated UI testing and the ways to handle them. Followings are some common challenges with automates UI testing − The very common issues while working with UI testing is the changes happens in UI. For example, it happens most of the time that buttons or textboxes etc. usually got change and creates issues for UI testing. Another issue with UI testing is the lack of DSL support. With this issue, it becomes very hard to understand what is being tested. The next common problem in UI testing is that there is lots of repetition or code duplication. It can be understood with the help of following lines of code − element(by.model(‘event.name’)).sendKeys(‘An Event’); element(by.model(‘event.name’)).sendKeys(‘Module 3’); element(by.model(‘event.name’)); Due to the above challenges, it becomes headache for maintenance. It is because we have to find all the instances, replace with the new name, selector & other code. We also need to spend lots of time to keep tests in line with refactoring. Another challenge in UI testing is the happening of lots of failures in tests. We have seen some common challenges of UI testing. Some of the ways to handle such challenges are as follows − The very first option for handling the above challenges is to update the references manually. The problem with this option is that we must do the manual change in the code as well as our tests. This can be done when you have one or two tests files but what if you have hundreds of tests files in a project? Another option for handling above challenges is to use page objects. A page object is basically a plain JavaScript that encapsulates the properties of an Angular template. For example, the following specification file is written without and with page objects to understand the difference − Without Page Objects describe('angularjs homepage', function() { it('should greet the named user', function() { browser.get('http://www.angularjs.org'); element(by.model('yourName')).sendKeys('Julie'); var greeting = element(by.binding('yourName')); expect(greeting.getText()).toEqual('Hello Julie!'); }); }); With Page Objects For writing the code with Page Objects, the first thing we need to do is to create a Page Object. Hence, a Page Object for the above example could look like this − var AngularHomepage = function() { var nameInput = element(by.model('yourName')); var greeting = element(by.binding('yourName')); this.get = function() { browser.get('http://www.angularjs.org'); }; this.setName = function(name) { nameInput.sendKeys(name); }; this.getGreetingText = function() { return greeting.getText(); }; }; module.exports = new AngularHomepage(); We have seen the use of page objects in the above example to handle the challenges of UI testing. Next, we are going to discuss how we can use them to organize the tests. For this we need to modify the test script without modifying the functionality of the test script. To understand this concept we are taking the above configuration file with page objects. We need to modify the test script as follows − var angularHomepage = require('./AngularHomepage'); describe('angularjs homepage', function() { it('should greet the named user', function() { angularHomepage.get(); angularHomepage.setName('Julie'); expect(angularHomepage.getGreetingText()).toEqual ('Hello Julie!'); }); }); Here, note that the path to the page object will be relative to your specification. On the same note, we can also separate our test suite into various test suites. The configuration file then can be changed as follows exports.config = { // The address of a running selenium server. seleniumAddress: 'http://localhost:4444/wd/hub', // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Spec patterns are relative to the location of the spec file. They may // include glob patterns. suites: { homepage: 'tests/e2e/homepage/**/*Spec.js', search: ['tests/e2e/contact_search/**/*Spec.js', 'tests/e2e/venue_search/**/*Spec.js'] }, // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, // Use colors in the command line report. } }; Now, we can easily switch between running one or the other suite of tests. The following command will run only the homepage section of the test − protractor protractor.conf.js --suite homepage Similarly, we can run specific suites of tests with the command as follows − protractor protractor.conf.js --suite homepage,search Now that we have seen all the concepts of Protractor in the previous chapters, let us understand the debugging concepts in detail in this chapter. End-to-end (e2e) tests are very difficult to debug because they depend on the whole ecosystem of that application. We have seen that they depend upon various actions or particularly we can say that on prior actions like login and sometimes they depend on the permission. Another difficulty in debugging e2e tests is its dependency on WebDriver because it acts differently with different operating systems and browsers. Finally, debugging e2e tests also generates long error messages and makes it difficult to separate browser related issues and test process errors. There can be various reasons for the failure of test suites and followings are some well-known failure types − When a command cannot be completed, an error is thrown by WebDriver. For example, a browser cannot get the defined address, or an element is not found as expected. An unexpected browser and OS-related failure happens when it fails to update the web driver manager. The failure of Protractor for Angular happens when Protractor didn’t find Angular in the library as expected. In this kind of failure, Protractor will fail when the useAllAngular2AppRoots parameter is not found in the configuration. It happens because, without this, the test process will look at one single root element while expecting more than one element in the process. This kind of failure happens when the test specification hit a loop or a long pool and fails to return the data in time. One of the most common test failures that shows what a normal expectation failure looks like. Suppose, if you have written test cases and they got failed then it is very important to know how to debug those test cases because it would be very hard to find the exact place where the error has occurred. While working with Protractor, you will get some long errors in red color font in the command line. The ways to debug in Protractor are explained here &miuns; Using the pause method to debug the test cases in Protractor is one of the easiest ways. We can type the following command at the place we want to pause our test code &miuns; browser.pause(); When the running codes hits the above command, it will pause the running program at that point. After that we can give the following commands according to our preference − Whenever a command has exhausted, we must type C to move forward. If you will not type C, the test will not run the full code and it will fail due to Jasmine time out error. The benefit of interactive mode is that we can send the WebDriver commands to our browser. If we want to enter into the interactive mode, then type repl. For exiting the test from pause state and continuing the test from where it has stopped, we need to type Ctrl-C. In this example, we are having the below specification file named example_debug.js, protractor tries to identify an element with locator by.binding(‘mmmm’) but the URL(https://angularjs.org/ page has no element with specified locator. describe('Suite for protractor debugger',function(){ it('Failing spec',function(){ browser.get("http://angularjs.org"); element(by.model('yourName')).sendKeys('Vijay'); //Element doesn't exist var welcomeText = element(by.binding('mmmm')).getText(); expect('Hello '+welcomeText+'!').toEqual('Hello Ram!') }); }); Now, for executing the above test we need to add browser.pause() code, where you want to pause the test, in the above specification file. It will look as follows − describe('Suite for protractor debugger',function(){ it('Failing spec',function(){ browser.get("http://angularjs.org"); browser.pause(); element(by.model('yourName')).sendKeys('Vijay'); //Element doesn't exist var welcomeText = element(by.binding('mmmm')).getText(); expect('Hello '+welcomeText+'!').toEqual('Hello Ram!') }); }); But before executing, we need to do some changes in the configuration file also. We are doing the following changes in earlier used configuration file, named example_configuration.js in previous chapter − // An example configuration file. exports.config = { directConnect: true, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Framework to use. Jasmine is recommended. framework: 'jasmine', // Spec patterns are relative to the current working directory when // protractor is called. specs: ['example_debug.js'], allScriptsTimeout: 999999, jasmineNodeOpts: { defaultTimeoutInterval: 999999 }, onPrepare: function () { browser.manage().window().maximize(); browser.manage().timeouts().implicitlyWait(5000); } }; Now, run the following command − protractor example_configuration.js The debugger will start after the above command. Using the pause method to debug the test cases in Protractor is a bit advanced way. We can type the following command at the place we want to break our test code − browser.debugger(); It uses the node debugger to debug the test code. For running the above command, we must type the following command in a separate command prompt which has opened from the test project location − protractor debug protractor.conf.js In this method, we also need to type C in the terminal for continuing the test code. But opposite to pause method, in this method it is to be typed for only one time. In this example, we are using the same specification file named bexample_debug.js, used above. The only difference is that instead of browser.pause(), we need to use browser.debugger() where we want to break the test code. It will look as follows − describe('Suite for protractor debugger',function(){ it('Failing spec',function(){ browser.get("http://angularjs.org"); browser.debugger(); element(by.model('yourName')).sendKeys('Vijay'); //Element doesn't exist var welcomeText = element(by.binding('mmmm')).getText(); expect('Hello '+welcomeText+'!').toEqual('Hello Ram!') }); }); We are using the same configuration file, example_configuration.js, used in above example. Now, run the protractor test with following debug command line option protractor debug example_configuration.js The debugger will start after the above command. In this chapter, let us learn in detail about style guide for protractor. The style guide was created by two software engineers named, Carmen Popoviciu, front-end engineer at ING and Andres Dominguez, software engineer at Google. Hence, this style guide is also called Carmen Popoviciu and Google’s style guide for protractor. This style guide can be divided into the following five keypoints − Generic rules Project Structure Locator strategies Page Objects Test suites The following are some generic rules that must be taken care while using protractor for testing − This is the very first generic rule given by Carmen and Andres. They suggested that we must not perform e2e test on the code that already been unit tested. The main reason behind it is that the unit tests are much faster than e2e tests. Another reason is that we must have to avoid duplicate tests (don’t perform both unit and e2e testing) for saving our time. Another important point recommended is that we must have to use only one configuration file. Do not create configuration file for each environment you are testing. You can use grunt-protractor-coverage in order to set up different environments. We must have to avoid using IF statements or FOR loops in our test cases because if we do so then the test may pass without testing anything or it may run very slow. Protractor can run the test parallelly when sharing is enabled. These files are then executed across different browsers as and when they become available. Carmen and Andres recommended to make the test independent at least at file level because the order in which they will be run by protractor is uncertain and moreover it is quite easy to run a test in isolation. Another important key point regarding the style guide of Protractor is the structure of your project. The following is the recommendation about project structure − Carmen and Andres recommended that we must group our e2e tests in a structure that makes sense to the structure of your project. The reason behind this recommendation is that the finding of files would become easy and the folder structure would be more readable. This step will also separate e2e tests from unit tests. They recommended that the following kind of structure should be avoided − |-- project-folder |-- app |-- css |-- img |-- partials home.html profile.html contacts.html |-- js |-- controllers |-- directives |-- services app.js ... index.html |-- test |-- unit |-- e2e home-page.js home-spec.js profile-page.js profile-spec.js contacts-page.js contacts-spec.js On the other hand, they recommended the following kind of structure − |-- project-folder |-- app |-- css |-- img |-- partials home.html profile.html contacts.html |-- js |-- controllers |-- directives |-- services app.js ... index.html |-- test |-- unit |-- e2e |-- page-objects home-page.js profile-page.js contacts-page.js home-spec.js profile-spec.js contacts-spec.js The following are some locator strategies that must be taken care while using protractor for testing − This is the first locator strategies that is recommended in protractor style guide. The reasons behind the same is that XPath is requires lots of maintenance because markup is very easily subject to change. Moreover, XPath expressions are the slowest and very hard to debug. Protractor-specific locators such as by.model and by.binding are short, specific and easy to read. With the help of them it is very easy to write our locator also. View <ul class = "red"> <li>{{color.name}}</li> <li>{{color.shade}}</li> <li>{{color.code}}</li> </ul> <div class = "details"> <div class = "personal"> <input ng-model = "person.name"> </div> </div> For the above code, it is recommended to avoid the following − var nameElement = element.all(by.css('.red li')).get(0); var personName = element(by.css('.details .personal input')); On the other hand, the following is recommended to use − var nameElement = element.all(by.css('.red li')).get(0); var personName = element(by.css('.details .personal input')); var nameElement = element(by.binding('color.name')); var personName = element(by.model('person.name')); When no Protractor locators are available, then it is recommended to prefer by.id and by.css. We must have to avoid text-based locators such as by.linkText, by.buttonText and by.cssContaningText because text for buttons, links and labels frequently change over time. As discussed earlier, page objects encapsulate information about the elements on our application page and due to this help us write cleaner test cases. A very useful advantage of page objects is that they can be reused across multiple tests and in case if the template of our application has been changed, we only need to update the page object. Followings are some recommendations for page objects that must be taken care while using protractor for testing − It is recommended to use page objects to interact with the page under test because they can encapsulate information about the element on the page under test and they can be reused also. We should define each page object in its own file because it keeps the code clean and finding of things becomes easy. It is recommended that each page object should declare a single class so that we only need to export one class. For example, the following use of object file should be avoided − var UserProfilePage = function() {}; var UserSettingsPage = function() {}; module.exports = UserPropertiesPage; module.exports = UserSettingsPage; But on the other hand, following is recommended to use − /** @constructor */ var UserPropertiesPage = function() {}; module.exports = UserPropertiesPage; We should declare all the required modules at the top of the page object because it makes module dependencies clear and easy to find. It is recommended to instantiate all the page objects at the beginning of the test suite because this will separate dependencies from the test code as well as makes the dependencies available to all the specifications of the suite. We should not use expect() in page objects i.e. we should not make any assertions in our page objects because all the assertions must be done in test cases. Another reason is that the reader of the test should be able to understand the behavior of the application by reading the test cases only. 35 Lectures 3.5 hours SAYANTAN TARAFDAR 18 Lectures 3 hours LuckyTrainings Print Add Notes Bookmark this page
[ { "code": null, "e": 2080, "s": 1891, "text": "This chapter gives you an introduction to Protractor, where you will learn about the origin of this testing framework and why you have to choose this, working and limitations of this tool." }, { "code": null, "e": 2341, "s": 2080, "text": "Protractor is an open source end-to-end testing framework for Angular and AngularJS applications. It was built by Google on the top of WebDriver. It also serves as a replacement for the existing AngularJS E2E testing framework called “Angular Scenario Runner”." }, { "code": null, "e": 2708, "s": 2341, "text": "It also works as a solution integrator that combines powerful technologies such as NodeJS, Selenium, Jasmine, WebDriver, Cucumber, Mocha etc. Along with testing of AngularJS application, it also writes automated regression tests for normal web applications. It allows us to test our application just like a real user because it runs the test using an actual browser." }, { "code": null, "e": 2773, "s": 2708, "text": "The following diagram will give a brief overview of Protractor −" }, { "code": null, "e": 2818, "s": 2773, "text": "Observe that in the above diagram, we have −" }, { "code": null, "e": 2925, "s": 2818, "text": "Protractor − As discussed earlier, it is a wrapper over WebDriver JS especially designed for angular apps." }, { "code": null, "e": 3032, "s": 2925, "text": "Protractor − As discussed earlier, it is a wrapper over WebDriver JS especially designed for angular apps." }, { "code": null, "e": 3175, "s": 3032, "text": "Jasmine − It is basically a behavior-driven development framework for testing the JavaScript code. We can write the tests easily with Jasmine." }, { "code": null, "e": 3318, "s": 3175, "text": "Jasmine − It is basically a behavior-driven development framework for testing the JavaScript code. We can write the tests easily with Jasmine." }, { "code": null, "e": 3401, "s": 3318, "text": "WebDriver JS − It is a Node JS bindings implementation for selenium 2.0/WebDriver." }, { "code": null, "e": 3484, "s": 3401, "text": "WebDriver JS − It is a Node JS bindings implementation for selenium 2.0/WebDriver." }, { "code": null, "e": 3528, "s": 3484, "text": "Selenium − It simply automates the browser." }, { "code": null, "e": 3572, "s": 3528, "text": "Selenium − It simply automates the browser." }, { "code": null, "e": 3927, "s": 3572, "text": "As said earlier, Protractor is a replacement for the existing AngularJS E2E testing framework called “Angular Scenario Runner”. Basically, the origin of Protractor starts with the end of Scenario Runner. A question that arises here is why do we need to build Protractor? To understand this, we first need to check about its predecessor - Scenario Runner." }, { "code": null, "e": 4171, "s": 3927, "text": "Julie Ralph, the prime contributor to the development of Protractor, had the following experience with Angular Scenario Runner on other project within Google. This further became the motivation to build Protractor, specially to fill the gaps −" }, { "code": null, "e": 4531, "s": 4171, "text": "“We tried using Scenario Runner and we found that it really just couldn’t do the things that we needed to test. We needed to test things like logging in. Your login page is not an Angular page, and the Scenario Runner couldn’t deal with that. And it couldn’t deal with things like popups and multiple windows, navigating the browser history, stuff like that.”" }, { "code": null, "e": 4844, "s": 4531, "text": "The biggest advantage to the Protractor was the maturity of Selenium project and it wraps up its methods so that it can be easily used for Angular projects. The design of Protractor is built in such a way that it tests all layers such that web UI, backend services, persistence layer and so on of an application." }, { "code": null, "e": 5294, "s": 4844, "text": "As we know that almost all the applications are using JavaScript for development. The task of testers becomes difficult when JavaScript increases in size and becomes complex for applications due to the increasing number of the applications itself. Most of the times it becomes very difficult to capture the web elements in AngularJS applications, uses extended HTML syntax to express web application components, by using JUnit or Selenium WebDriver." }, { "code": null, "e": 5569, "s": 5294, "text": "The question here is that why Selenium Web Driver is not able to find AngularJS web elements? The reason is because AngularJS applications are having some extended HTML attributes like ng-repeater, ng-controller and ng-model etc. which are not included in Selenium locators." }, { "code": null, "e": 5937, "s": 5569, "text": "Here, the importance of Protractor comes into existence because Protractor on the top of Selenium can handle and control those extended HTML elements in AngularJS web applications. That is why we can say that most of the frameworks focus on conducting unit tests for AngularJS applications, Protractor used to do testing of the actual functionality of an application." }, { "code": null, "e": 6162, "s": 5937, "text": "Protractor, the testing framework, works in conjunction with Selenium to provide an automated test infrastructure for simulating a user’s interaction with an AngularJS application that is running in browser or mobile device." }, { "code": null, "e": 6241, "s": 6162, "text": "The working of Protractor can be understood with the help of following steps −" }, { "code": null, "e": 6359, "s": 6241, "text": "Step 1 − In the first step, we need to write the tests. It can be done with the help of Jasmine or Mocha or Cucumber." }, { "code": null, "e": 6477, "s": 6359, "text": "Step 1 − In the first step, we need to write the tests. It can be done with the help of Jasmine or Mocha or Cucumber." }, { "code": null, "e": 6593, "s": 6477, "text": "Step 2 − Now, we need to run the test which can be done with the help of Protractor. It is also called test runner." }, { "code": null, "e": 6709, "s": 6593, "text": "Step 2 − Now, we need to run the test which can be done with the help of Protractor. It is also called test runner." }, { "code": null, "e": 6782, "s": 6709, "text": "Step 3 − In this step, Selenium server will help to manage the browsers." }, { "code": null, "e": 6855, "s": 6782, "text": "Step 3 − In this step, Selenium server will help to manage the browsers." }, { "code": null, "e": 6939, "s": 6855, "text": "Step 4 − At last, the browser APIs are invoked with the help of Selenium WebDriver." }, { "code": null, "e": 7023, "s": 6939, "text": "Step 4 − At last, the browser APIs are invoked with the help of Selenium WebDriver." }, { "code": null, "e": 7103, "s": 7023, "text": "This open source end-to-end testing framework offers the following advantages −" }, { "code": null, "e": 7170, "s": 7103, "text": "An open source tool, Protractor is very easy to install and setup." }, { "code": null, "e": 7237, "s": 7170, "text": "An open source tool, Protractor is very easy to install and setup." }, { "code": null, "e": 7291, "s": 7237, "text": "Works well with Jasmine framework to create the test." }, { "code": null, "e": 7345, "s": 7291, "text": "Works well with Jasmine framework to create the test." }, { "code": null, "e": 7385, "s": 7345, "text": "Supports test driven development (TDD)." }, { "code": null, "e": 7425, "s": 7385, "text": "Supports test driven development (TDD)." }, { "code": null, "e": 7525, "s": 7425, "text": "Contains automatic waits which means we do not need to explicitly add waits and sleeps to our test." }, { "code": null, "e": 7625, "s": 7525, "text": "Contains automatic waits which means we do not need to explicitly add waits and sleeps to our test." }, { "code": null, "e": 7674, "s": 7625, "text": "Offers all the advantages of Selenium WebDriver." }, { "code": null, "e": 7723, "s": 7674, "text": "Offers all the advantages of Selenium WebDriver." }, { "code": null, "e": 7776, "s": 7723, "text": "Supports parallel testing through multiple browsers." }, { "code": null, "e": 7829, "s": 7776, "text": "Supports parallel testing through multiple browsers." }, { "code": null, "e": 7875, "s": 7829, "text": "Provides the benefit of auto-synchronization." }, { "code": null, "e": 7921, "s": 7875, "text": "Provides the benefit of auto-synchronization." }, { "code": null, "e": 7950, "s": 7921, "text": "Has excellent testing speed." }, { "code": null, "e": 7979, "s": 7950, "text": "Has excellent testing speed." }, { "code": null, "e": 8063, "s": 7979, "text": "This open source end-to-end testing framework possesses the following limitations −" }, { "code": null, "e": 8158, "s": 8063, "text": "Does not uncover any verticals in browser automation because it is a wrapper for WebDriver JS." }, { "code": null, "e": 8253, "s": 8158, "text": "Does not uncover any verticals in browser automation because it is a wrapper for WebDriver JS." }, { "code": null, "e": 8349, "s": 8253, "text": "Knowledge of JavaScript is essential for the user, because it is available only for JavaScript." }, { "code": null, "e": 8445, "s": 8349, "text": "Knowledge of JavaScript is essential for the user, because it is available only for JavaScript." }, { "code": null, "e": 8517, "s": 8445, "text": "Only provides front-end testing because it is a UI driven testing tool." }, { "code": null, "e": 8589, "s": 8517, "text": "Only provides front-end testing because it is a UI driven testing tool." }, { "code": null, "e": 8746, "s": 8589, "text": "Since the knowledge of JavaScript is essential for working with Protractor, in this chapter, let us understand the concepts of JavaScript testing in detail." }, { "code": null, "e": 9180, "s": 8746, "text": "JavaScript is the most popular dynamically typed and interpreted scripting language, but the most challenging task is to test the code. It is because, unlike other compiled languages like JAVA, and C++, there are no compilation steps in JavaScript that can help the tester to figure out errors. Besides, browser-based testing is very time consuming; hence there is a necessity for tools that support automated testing for JavaScript." }, { "code": null, "e": 9584, "s": 9180, "text": "It is always a good practice to write the test because it makes the code better; the issue with manual testing is that it is a bit time consuming and error prone. The process of manual testing is quite boring for programmer too as they need to repeat the process, writing test specs, change the code and refresh the browser several times. Besides, manual testing also slows down the development process." }, { "code": null, "e": 9815, "s": 9584, "text": "Due to the above reasons, it is always useful to have some tools that can automate these tests and help programmers to get rid of these repetitive and boring steps. What should a developer do to make the testing process automated?" }, { "code": null, "e": 10197, "s": 9815, "text": "Basically, a developer can implement the tool set in the CLI (Command Line Interpreter) or in the development IDE (Integrated development environment). Then, these tests will run continuously in a separate process even without the input from the developer. Automated testing of JavaScript is also not new and lots of tools like Karma, Protractor, CasperJS etc. have been developed." }, { "code": null, "e": 10456, "s": 10197, "text": "There can be different tests for different purposes. For example, some tests are written to check the behavior of functions in a program, while some other are written to test the flow of a module or feature. Thus, we have the following two types of testing −" }, { "code": null, "e": 10805, "s": 10456, "text": "The testing is done on the smallest testable part of the program called unit. The unit is basically tested in isolation without any kind of dependency of that unit on the other parts. In case of JavaScript, the individual method or function having a specific behavior can be a unit of code and these units of code must be tested in an isolated way." }, { "code": null, "e": 11053, "s": 10805, "text": "One of the advantages of unit testing is that the testing of units can be done in any order because the units are independent of each other. Another advantage of unit testing which really counts is that it can run the test at any time as follows −" }, { "code": null, "e": 11105, "s": 11053, "text": "From the very beginning of the development process." }, { "code": null, "e": 11161, "s": 11105, "text": "After completing the development of any module/feature." }, { "code": null, "e": 11197, "s": 11161, "text": "After modifying any module/feature." }, { "code": null, "e": 11255, "s": 11197, "text": "After adding any new feature in the existing application." }, { "code": null, "e": 11397, "s": 11255, "text": "For automated unit testing of JavaScript applications, we can choose from many testing tools and frameworks such as Mocha, Jasmine and QUnit." }, { "code": null, "e": 11573, "s": 11397, "text": "It may be defined as the testing methodology used to test whether the flow of the application from start to finish (from one end to another end) is working fine as per design." }, { "code": null, "e": 11808, "s": 11573, "text": "End-to-end testing is also called function/flow testing. Unlike unit testing, end-to-end testing tests how individual components work together as an application. This is the main difference between unit testing and end-to-end testing." }, { "code": null, "e": 12048, "s": 11808, "text": "For example, suppose if we have a registration module where the user needs to provide some valid information to complete the registration then the E2E testing for that particular module will follow following steps to complete the testing −" }, { "code": null, "e": 12096, "s": 12048, "text": "First, it will load/compile the form or module." }, { "code": null, "e": 12169, "s": 12096, "text": "Now, it will get the DOM (Document object model) of the form’s elements." }, { "code": null, "e": 12258, "s": 12169, "text": "Next, trigger the click event of the submit button for checking if it is working or not." }, { "code": null, "e": 12327, "s": 12258, "text": "Now, for validation purpose collect the value from the input fields." }, { "code": null, "e": 12371, "s": 12327, "text": "Next, the input fields should be validated." }, { "code": null, "e": 12427, "s": 12371, "text": "For testing purpose, call a fake API to store the data." }, { "code": null, "e": 12513, "s": 12427, "text": "Every step gives its own results which will be compared with the expected result set." }, { "code": null, "e": 12862, "s": 12513, "text": "Now, the question that arises is, while this kind of E2E or functional testing can be performed manually also, why we need automation for this? The main reason is that automation will make this test process easy. Some of the available tools that can be easily integrate with any application, for this purpose are Selenium, PhantomJS and Protractor." }, { "code": null, "e": 12992, "s": 12862, "text": "We have various testing tools and frameworks for Angular testing. The following are some of the well-known tools and frameworks −" }, { "code": null, "e": 13518, "s": 12992, "text": "Karma, created by Vojta Jina, is a test runner. Originally this project was called Testacular. It is not a test framework, which means that it gives us the ability to easily and automatically run JavaScript unit tests on real browsers. Karma was built for AngularJS because before Karma there was no automated testing tool for web-based JavaScript developers. On the other hand, with the automation provided by Karma, developers can run a simple single command and determine whether an entire test suite has passed or failed." }, { "code": null, "e": 13599, "s": 13518, "text": "The following are some pros of using Karma in comparison to the manual process −" }, { "code": null, "e": 13656, "s": 13599, "text": "Automates tests in multiple browsers as well as devices." }, { "code": null, "e": 13698, "s": 13656, "text": "Monitors files for errors and fixes them." }, { "code": null, "e": 13741, "s": 13698, "text": "Provides online support and documentation." }, { "code": null, "e": 13801, "s": 13741, "text": "Eases the integration with a continuous integration server." }, { "code": null, "e": 13847, "s": 13801, "text": "The followings are some cons of using Karma −" }, { "code": null, "e": 13950, "s": 13847, "text": "The main disadvantage of using Karma is that it requires an additional tool to configure and maintain." }, { "code": null, "e": 14138, "s": 13950, "text": "If you are using Karma test runner with Jasmine, then less documentation is available for finding information about setting up your CSS in the case of having multiple ids for one element." }, { "code": null, "e": 14594, "s": 14138, "text": "Jasmine, a behavior-driven development framework for testing JavaScript code, is developed at Pivotal Labs. Before the active development of Jasmine framework, a similar unit testing framework named JsUnit was also developed by Pivotal Labs, which has an inbuilt test runner. The browsers tests can be run through Jasmine tests by including SpecRunner.html file or by using it as a command line test runner also. It can be used with or without Karma also." }, { "code": null, "e": 14642, "s": 14594, "text": "The followings are some pros of using Jasmine −" }, { "code": null, "e": 14701, "s": 14642, "text": "A framework independent of browser, platform and language." }, { "code": null, "e": 14760, "s": 14701, "text": "A framework independent of browser, platform and language." }, { "code": null, "e": 14841, "s": 14760, "text": "Supports test driven development (TDD) along with behavioral driven development." }, { "code": null, "e": 14922, "s": 14841, "text": "Supports test driven development (TDD) along with behavioral driven development." }, { "code": null, "e": 14958, "s": 14922, "text": "Has default integration with Karma." }, { "code": null, "e": 14994, "s": 14958, "text": "Has default integration with Karma." }, { "code": null, "e": 15021, "s": 14994, "text": "Easy to understand syntax." }, { "code": null, "e": 15048, "s": 15021, "text": "Easy to understand syntax." }, { "code": null, "e": 15159, "s": 15048, "text": "Provides test spies, fakes and pass-through functionalities which assist with testing as additional functions." }, { "code": null, "e": 15270, "s": 15159, "text": "Provides test spies, fakes and pass-through functionalities which assist with testing as additional functions." }, { "code": null, "e": 15312, "s": 15270, "text": "The following is a con of using Jasmine −" }, { "code": null, "e": 15447, "s": 15312, "text": "The tests must be return by the user as they change because there is no file-watching feature available in Jasmine while running test." }, { "code": null, "e": 15582, "s": 15447, "text": "The tests must be return by the user as they change because there is no file-watching feature available in Jasmine while running test." }, { "code": null, "e": 15940, "s": 15582, "text": "Mocha, written for Node.js applications, is a testing framework but it also supports browser testing. It is quite like Jasmine but the major difference between them is that Mocha needs some plugin and library because it cannot run standalone as a test framework. On the other hand, Jasmine is standalone. However, Mocha is more flexible to use than Jasmine." }, { "code": null, "e": 15985, "s": 15940, "text": "The following are some pros of using Mocha −" }, { "code": null, "e": 16030, "s": 15985, "text": "Mocha is very easy to install and configure." }, { "code": null, "e": 16070, "s": 16030, "text": "User-friendly and simple documentation." }, { "code": null, "e": 16115, "s": 16070, "text": "Contains plugins with several node projects." }, { "code": null, "e": 16160, "s": 16115, "text": "The following are some cons of using Mocha −" }, { "code": null, "e": 16213, "s": 16160, "text": "It needs separate modules for assertions, spies etc." }, { "code": null, "e": 16277, "s": 16213, "text": "It also requires additional configuration for using with Karma." }, { "code": null, "e": 16565, "s": 16277, "text": "QUint, originally developed by John Resig in 2008 as part of jQuery, is a powerful yet easy-to-use JavaScript unit test suite. It can be used to test any generic JavaScript code. Although it focuses on testing JavaScript in the browser, yet it is very convenient to use by the developer." }, { "code": null, "e": 16610, "s": 16565, "text": "The following are some pros of using QUnit −" }, { "code": null, "e": 16641, "s": 16610, "text": "Easy to install and configure." }, { "code": null, "e": 16681, "s": 16641, "text": "User-friendly and simple documentation." }, { "code": null, "e": 16721, "s": 16681, "text": "The following is a con of using QUnit −" }, { "code": null, "e": 16809, "s": 16721, "text": "It was mainly developed for jQuery and hence not so good for use with other frameworks." }, { "code": null, "e": 17108, "s": 16809, "text": "Selenium, originally developed by Jason Huggins in 2004 as an internal tool at ThoughtWorks, is an open source testing automation tool. Selenium defines itself as “Selenium automates browsers. That’s it!”. Automation of browsers means that the developers can interact with the browsers very easily." }, { "code": null, "e": 17156, "s": 17108, "text": "The following are some pros of using Selenium −" }, { "code": null, "e": 17184, "s": 17156, "text": "Contains large feature set." }, { "code": null, "e": 17214, "s": 17184, "text": "Supports distributed testing." }, { "code": null, "e": 17268, "s": 17214, "text": "Has SaaS support through services such as Sauce Labs." }, { "code": null, "e": 17337, "s": 17268, "text": "Easy to use with simple documentations and rich resources available." }, { "code": null, "e": 17386, "s": 17337, "text": "The followings are some cons of using Selenium −" }, { "code": null, "e": 17470, "s": 17386, "text": "A main disadvantage of using Selenium is that it must be run as a separate process." }, { "code": null, "e": 17552, "s": 17470, "text": "Configuration is a bit cumbersome as the developer needs to follow several steps." }, { "code": null, "e": 17682, "s": 17552, "text": "In the previous chapters, we have learnt the basics of Protractor. In this chapter, let us learn how to install and configure it." }, { "code": null, "e": 17777, "s": 17682, "text": "We need to satisfy the following prerequisites before installing Protractor on your computer −" }, { "code": null, "e": 18013, "s": 17777, "text": "Protractor is a Node.js module, hence the very important prerequisite is that we must have Node.js installed on our computer. We are going to install Protractor package using npm (a JavaScript package manager), that comes with Node.js." }, { "code": null, "e": 18269, "s": 18013, "text": "For installing Node.js please follow the official link − https://nodejs.org/en/download/. After installing Node.js, you can check the version of Node.js and npm by writing the command node --version and npm --version in the command prompt as shown below −" }, { "code": null, "e": 18488, "s": 18269, "text": "Google Chrome, a web browser built by Google, will be used to run end-to-end tests in Protractor without the need for a Selenium server. You can download chrome by clicking on the link − https://www.google.com/chrome/." }, { "code": null, "e": 18590, "s": 18488, "text": "This tool is provided with the Protractor npm module and allows us to interact with web applications." }, { "code": null, "e": 18695, "s": 18590, "text": "After installing Node.js on our computer, we can install Protractor with the help of following command −" }, { "code": null, "e": 18722, "s": 18695, "text": "npm install -g protractor\n" }, { "code": null, "e": 18869, "s": 18722, "text": "Once protractor is successfully installed, we can check its version by writing protractor --version command in the command prompt as shown below −" }, { "code": null, "e": 19005, "s": 18869, "text": "After installing Protractor, we need to install Selenium WebDriver for Chrome. It can be installed with the help of following command −" }, { "code": null, "e": 19031, "s": 19005, "text": "webdriver-manager update\n" }, { "code": null, "e": 19145, "s": 19031, "text": "The above command will create a Selenium directory which contains the required Chrome driver used in the project." }, { "code": null, "e": 19390, "s": 19145, "text": "We can confirm the installation and configurati\non of Protractor by doing a slightly changing the conf.js provided in the example after installing Protractor. You can find this conf.js file in the root directory node_modules/Protractor/example." }, { "code": null, "e": 19507, "s": 19390, "text": "For this, first create a new file named testingconfig.js in the same directory i.e. node_modules/Protractor/example." }, { "code": null, "e": 19602, "s": 19507, "text": "Now, in the conf.js file, under the source file declaration parameter, write testingconfig.js." }, { "code": null, "e": 19723, "s": 19602, "text": "Next, save and close all the files and open command prompt. Run the conf.js file as shown in the screenshot given below." }, { "code": null, "e": 19825, "s": 19723, "text": "The configuration and installation of Protractor is successful if you got the output as shown below −" }, { "code": null, "e": 20067, "s": 19825, "text": "The above output shows that there is no specification because we provided the empty file at source file declaration parameter in conf.js file. But from the above output, we can see that both protractor and WebDriver are running successfully." }, { "code": null, "e": 20177, "s": 20067, "text": "While installing and configuring Protractor and WebDriver, we might come across the following common issues −" }, { "code": null, "e": 20398, "s": 20177, "text": "It is the most common issue while installing WebDriver. This issue arises if you do not update the WebDriver. Note that we must update WebDriver, otherwise we would not be able to reference it to Protractor installation." }, { "code": null, "e": 20683, "s": 20398, "text": "Another common issue is that after running Protractor, it shows that unable to find tests. For this,we must have to ensure that the relative paths, filenames or extensions are correct. We also need to write conf.js file very carefully because it starts with configuration file itself." }, { "code": null, "e": 20978, "s": 20683, "text": "As discussed earlier, Protractor is an open source, end-to-end testing framework for Angular and AngularJS applications. It is Node.js program. On the other hand, Selenium is a browser automation framework that includes the Selenium Server, the WebDriver APIs and the WebDriver browser drivers." }, { "code": null, "e": 21403, "s": 20978, "text": "If we talk about the conjunction of Protractor and Selenium, Protractor can work with Selenium server to provide an automated test infrastructure. The infrastructure can simulate user’s interaction with an angular application that is running in a browser or on mobile device. The conjunction of Protractor and Selenium can be divided into three partitions namely test, server and Browser, as shown in the following diagram −" }, { "code": null, "e": 21514, "s": 21403, "text": "As we have seen in the above diagram, a test using Selenium WebDriver involves the following three processes −" }, { "code": null, "e": 21531, "s": 21514, "text": "The test scripts" }, { "code": null, "e": 21542, "s": 21531, "text": "The server" }, { "code": null, "e": 21554, "s": 21542, "text": "The browser" }, { "code": null, "e": 21635, "s": 21554, "text": "In this section, let us discuss the communication between these three processes." }, { "code": null, "e": 21913, "s": 21635, "text": "The communication between the first two processes - the test scripts and the server depends upon the working of Selenium Server. In other words, we can say that the way Selenium server is running will give the shape to the communication process between test scripts and server." }, { "code": null, "e": 22187, "s": 21913, "text": "Selenium server can run locally on our machine as standalone Selenium Server (selenium-server-standalone.jar) or it can run remotely via a service (Sauce Labs). In case of standalone Selenium server, there would be an http communication between Node.js and selenium server." }, { "code": null, "e": 22553, "s": 22187, "text": "As we know that the server is responsible for forwarding commands to the browser after interpreting the same from the test scripts. That is why server and the browser also require a communication medium and here the communication is done with the help of JSON WebDriver Wire Protocol. The browser extended with Browser Driver that is used to interpret the commands." }, { "code": null, "e": 22685, "s": 22553, "text": "The above concept about Selenium WebDriver processes and their communication can be understood with the help of following diagram −" }, { "code": null, "e": 22924, "s": 22685, "text": "While working with Protractor, the very first process, that is test script is run using Node.js but before performing any action on the browser it will send an extra command to make it sure that the application being tested is stabilized." }, { "code": null, "e": 23268, "s": 22924, "text": "Selenium Server acts like a proxy server in between our test script and the browser driver. It basically forwards the command from our test script to the WebDriver and returns the responses from the WebDriver to our test script. There are following options for setting up the Selenium server which are included in conf.js file of test script −" }, { "code": null, "e": 23570, "s": 23268, "text": "If we want to run the server on our local machine, we need to install standalone selenium server. The prerequisite to install standalone selenium server is JDK (Java Development Kit). We must have JDK installed on our local machine. We can check it by running the following command from command line −" }, { "code": null, "e": 23585, "s": 23570, "text": "java -version\n" }, { "code": null, "e": 23676, "s": 23585, "text": "Now, we have the option to install and start Selenium Server manually or from test script." }, { "code": null, "e": 23880, "s": 23676, "text": "For installing and starting Selenium server manually, we need to use WebDriver-Manager command line tool that comes with Protractor. The steps for installing and starting Selenium server are as follows −" }, { "code": null, "e": 24016, "s": 23880, "text": "Step 1 − The first step is to install the Selenium server and ChromeDriver. It can be done with the help of running following command −" }, { "code": null, "e": 24042, "s": 24016, "text": "webdriver-manager update\n" }, { "code": null, "e": 24146, "s": 24042, "text": "Step 2 − Next, we need to start the server. It can be done with the help of running following command −" }, { "code": null, "e": 24171, "s": 24146, "text": "webdriver-manager start\n" }, { "code": null, "e": 24331, "s": 24171, "text": "Step 3 − At last we need to set seleniumAddress in config file to the address of the running server. The default address would be http://localhost:4444/wd/hub." }, { "code": null, "e": 24438, "s": 24331, "text": "For starting Selenium server from a Test Script, we need to set the following options in our config file −" }, { "code": null, "e": 24577, "s": 24438, "text": "Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar." }, { "code": null, "e": 24716, "s": 24577, "text": "Location of jar file − We need to set the location of jar file for standalone Selenium server in config file by setting seleniumServerJar." }, { "code": null, "e": 24905, "s": 24716, "text": "Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444." }, { "code": null, "e": 25094, "s": 24905, "text": "Specifying the port − We also need to specify the port to use to start the standalone Selenium Server. It can be specified in config file by setting seleniumPort. The default port is 4444." }, { "code": null, "e": 25350, "s": 25094, "text": "Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag." }, { "code": null, "e": 25606, "s": 25350, "text": "Array of command line options − We also need to set the array of command line options to pass to the server. It can be specified in config file by setting seleniumArgs. If you need full list of array of commands, then start the server with the -help flag." }, { "code": null, "e": 25898, "s": 25606, "text": "Another option for running our test is to use Selenium server remotely. The prerequisite for using server remotely is that we must have an account with a service that hosts the server. While working with Protractor we have the built-in support for the following services hosting the server −" }, { "code": null, "e": 26083, "s": 25898, "text": "For using TestObject as the remote Selenium Server, we need to set the testobjectUser, the user name of our TestObject account and testobjectKey, the API key of our TestObject account." }, { "code": null, "e": 26278, "s": 26083, "text": "For using BrowserStack as the remote Selenium Server, we need to set the browserstackUser, the user name of our BrowserStack account and browserstackKey, the API key of our BrowserStack account." }, { "code": null, "e": 26453, "s": 26278, "text": "For using Sauce Labs as the remote Selenium Server, we need to set the sauceUser, the user name of our Sauce Labs account and SauceKey, the API key of our Sauce Labs account." }, { "code": null, "e": 26622, "s": 26453, "text": "For using Kobiton as the remote Selenium Server we need to set the kobitonUser, the user name of our Kobiton account and kobitonKey, the API key of our Kobiton account." }, { "code": null, "e": 26875, "s": 26622, "text": "One more option for running our test is to connect to the Browser Driver directly without using Selenium server. Protractor can test directly, without the use of Selenium Server, against Chrome and Firefox by setting directConnect: true in config file." }, { "code": null, "e": 27046, "s": 26875, "text": "Before configuring and setting up the browser, we need to know which browsers are supported by Protractor. The following is the list of browsers supported by Protractor −" }, { "code": null, "e": 27059, "s": 27046, "text": "ChromeDriver" }, { "code": null, "e": 27073, "s": 27059, "text": "FirefoxDriver" }, { "code": null, "e": 27086, "s": 27073, "text": "SafariDriver" }, { "code": null, "e": 27095, "s": 27086, "text": "IEDriver" }, { "code": null, "e": 27113, "s": 27095, "text": "Appium-iOS/Safari" }, { "code": null, "e": 27135, "s": 27113, "text": "Appium-Android/Chrome" }, { "code": null, "e": 27146, "s": 27135, "text": "Selendroid" }, { "code": null, "e": 27156, "s": 27146, "text": "PhantomJS" }, { "code": null, "e": 27323, "s": 27156, "text": "For setting and configuring the browser, we need to move to config file of Protractor because the browser setup is done within the capabilities object of config file." }, { "code": null, "e": 27408, "s": 27323, "text": "For setting up the Chrome Browser, we need to set the capabilities object as follows" }, { "code": null, "e": 27454, "s": 27408, "text": "capabilities: {\n 'browserName': 'chrome'\n}\n" }, { "code": null, "e": 27632, "s": 27454, "text": "We can also add Chrome-Specific options which are nested in the chromeOptions and its full list can be seen at https://sites.google.com/a/chromium.org/chromedriver/capabilities." }, { "code": null, "e": 27748, "s": 27632, "text": "For example, if you want to add FPS-counter in the upper right, then it can be done as follows in the config file −" }, { "code": null, "e": 27862, "s": 27748, "text": "capabilities: {\n 'browserName': 'chrome',\n 'chromeOptions': {\n 'args': ['show-fps-counter=true']\n }\n}," }, { "code": null, "e": 27950, "s": 27862, "text": "For setting up the Firefox browser, we need to set the capabilities object as follows −" }, { "code": null, "e": 27997, "s": 27950, "text": "capabilities: {\n 'browserName': 'firefox'\n}\n" }, { "code": null, "e": 28182, "s": 27997, "text": "We can also add Firefox-Specific options which are nested in the moz:firefoxOptions object and its full list can be seen at https://github.com/mozilla/geckodriver#firefox-capabilities." }, { "code": null, "e": 28300, "s": 28182, "text": "For example, if you want to run your test on Firefox in safe mode then it can be done as follows in the config file −" }, { "code": null, "e": 28408, "s": 28300, "text": "capabilities: {\n 'browserName': 'firefox',\n 'moz:firefoxOptions': {\n 'args': ['—safe-mode']\n }\n}," }, { "code": null, "e": 28546, "s": 28408, "text": "For setting up any other browser than Chrome or Firefox, we need to install a separate binary from https://docs.seleniumhq.org/download/." }, { "code": null, "e": 28731, "s": 28546, "text": "Actually, PhantomJS is no longer supported because of its crashing issues. Instead of that it is recommended to use headless Chrome or headless Firefox. They can be set up as follows −" }, { "code": null, "e": 28824, "s": 28731, "text": "For setting up headless Chrome, we need to start Chrome with the –headless flag as follows −" }, { "code": null, "e": 28969, "s": 28824, "text": "capabilities: {\n 'browserName': 'chrome',\n 'chromeOptions': {\n 'args': [“--headless”, “--disable-gpu”, “--window-size=800,600”]\n }\n}," }, { "code": null, "e": 29064, "s": 28969, "text": "For setting up headless Firefox, we need to start Firefox with the –headless flag as follows −" }, { "code": null, "e": 29173, "s": 29064, "text": "capabilities: {\n 'browserName': 'firefox',\n 'moz:firefoxOptions': {\n 'args': [“--headless”]\n }\n}," }, { "code": null, "e": 29293, "s": 29173, "text": "We can also test against multiple browsers. For this we need to use multiCapabilities configuration option as follows −" }, { "code": null, "e": 29377, "s": 29293, "text": "multiCapabilities: [{\n 'browserName': 'chrome'\n},{\n 'browserName': 'firefox'\n}]" }, { "code": null, "e": 29647, "s": 29377, "text": "Two BDD (Behavior driven development) test frameworks, Jasmine and Mocha are supported by Protractor. Both frameworks are based on JavaScript and Node.js. The syntax, report and scaffolding, required for writing and managing the tests, are provided by these frameworks." }, { "code": null, "e": 29700, "s": 29647, "text": "Next, we see how we can install various frameworks −" }, { "code": null, "e": 29867, "s": 29700, "text": "It is the default test framework for Protractor. When you install Protractor, you will get Jasmine 2.x version with it. We do not need to get it installed separately." }, { "code": null, "e": 30152, "s": 29867, "text": "Mocha is another JavaScript test framework basically running on Node.js. For using Mocha as our test framework, we need to use the BDD (Behavior driven development) interface and Chai assertions with Chai As Promised. The installation can be done with the help of following commands −" }, { "code": null, "e": 30220, "s": 30152, "text": "npm install -g mocha\nnpm install chai\nnpm install chai-as-promised\n" }, { "code": null, "e": 30458, "s": 30220, "text": "As you can see, -g option is used while installing mocha, it is because we have installed Protractor globally using the -g option. After installing it, we need to require and set up Chai inside our test files. It can be done as follows −" }, { "code": null, "e": 30588, "s": 30458, "text": "var chai = require('chai');\nvar chaiAsPromised = require('chai-as-promised');\nchai.use(chaiAsPromised);\nvar expect = chai.expect;" }, { "code": null, "e": 30638, "s": 30588, "text": "After this, we can use Chai As Promised as such −" }, { "code": null, "e": 30701, "s": 30638, "text": "expect(myElement.getText()).to.eventually.equal('some text');\n" }, { "code": null, "e": 30888, "s": 30701, "text": "Now, we need to set the framework property to mocha of config file by adding framework: ‘mocha’. The options like ‘reporter’ and ‘slow’ for mocha can be added in config file as follows −" }, { "code": null, "e": 30936, "s": 30888, "text": "mochaOpts: {\n reporter: \"spec\", slow: 3000\n}\n" }, { "code": null, "e": 31113, "s": 30936, "text": "For using Cucumber as our test framework, we need to integrate it with Protractor with framework option custom. The installation can be done with the help of following commands" }, { "code": null, "e": 31191, "s": 31113, "text": "npm install -g cucumber\nnpm install --save-dev protractor-cucumber-framework\n" }, { "code": null, "e": 31517, "s": 31191, "text": "As you can see, -g option is used while installing Cucumber, it is because we have installed Protractor globally i.e. with -g option. Next, we need to set the framework property to custom of config file by adding framework: ‘custom’ and frameworkPath: ‘Protractor-cucumber-framework’ to the config file named cucumberConf.js." }, { "code": null, "e": 31643, "s": 31517, "text": "The sample code shown below is a basic cucumberConf.js file which can be used to run cucumber feature files with Protractor −" }, { "code": null, "e": 32232, "s": 31643, "text": "exports.config = {\n seleniumAddress: 'http://localhost:4444/wd/hub',\n\n baseUrl: 'https://angularjs.org/',\n\n capabilities: {\n browserName:'Firefox'\n },\n\n framework: 'custom',\n\n frameworkPath: require.resolve('protractor-cucumber-framework'),\n\n specs: [\n './cucumber/*.feature'\n ],\n\n // cucumber command line options\n cucumberOpts: {\n require: ['./cucumber/*.js'],\n tags: [],\n strict: true,\n format: [\"pretty\"],\n 'dry-run': false,\n compiler: []\n },\n onPrepare: function () {\n browser.manage().window().maximize();\n }\n};" }, { "code": null, "e": 32310, "s": 32232, "text": "In this chapter, let us understand how to write the first test in Protractor." }, { "code": null, "e": 32360, "s": 32310, "text": "Protractor needs the following two files to run −" }, { "code": null, "e": 32533, "s": 32360, "text": "It is one of the important files to run Protractor. In this file, we will write our actual test code. The test code is written by using the syntax of our testing framework." }, { "code": null, "e": 32724, "s": 32533, "text": "For example, if we are using Jasmine framework, then the test code will be written by using the syntax of Jasmine. This file will contain all the functional flows and assertions of the test." }, { "code": null, "e": 32833, "s": 32724, "text": "In simple words, we can say that this file contains the logic and locators to interact with the application." }, { "code": null, "e": 32963, "s": 32833, "text": "The following is a simple script, TestSpecification.js, having the test case to navigate to an URL and check for the page title −" }, { "code": null, "e": 33344, "s": 32963, "text": "//TestSpecification.js\ndescribe('Protractor Demo', function() {\n it('to check the page title', function() {\n browser.ignoreSynchronization = true;\n browser.get('https://www.tutorialspoint.com/tutorialslibrary.htm');\n browser.driver.getTitle().then(function(pageTitle) {\n expect(pageTitle).toEqual('Free Online Tutorials and Courses');\n });\n });\n});" }, { "code": null, "e": 33411, "s": 33344, "text": "The code of above specification file can be explained as follows −" }, { "code": null, "e": 33655, "s": 33411, "text": "It is the global variable created by Protractor to handle all the browser level commands. It is basically a wrapper around an instance of WebDriver. browser.get() is a simple Selenium method that will tell Protractor to load a particular page." }, { "code": null, "e": 33902, "s": 33655, "text": "describe and it − Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas ‘it’ contains some of the test scenarios. We can have multiple ‘it’ blocks in our test case program." }, { "code": null, "e": 34149, "s": 33902, "text": "describe and it − Both are the syntaxes of Jasmine test framework. The ’Describe’ is used to contain the end to end flow of our test case whereas ‘it’ contains some of the test scenarios. We can have multiple ‘it’ blocks in our test case program." }, { "code": null, "e": 34246, "s": 34149, "text": "Expect − It is an assertion where we are comparing the web page title with some predefined data." }, { "code": null, "e": 34343, "s": 34246, "text": "Expect − It is an assertion where we are comparing the web page title with some predefined data." }, { "code": null, "e": 34592, "s": 34343, "text": "ignoreSynchronization − It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to “true”." }, { "code": null, "e": 34841, "s": 34592, "text": "ignoreSynchronization − It is a tag of browser which is used when we will try to test non-angular websites. Protractor expects to work with angular websites only but if we want to work with non-angular websites, then this tag must be set to “true”." }, { "code": null, "e": 34987, "s": 34841, "text": "As the name suggests, this file provides explanations for all the Protractor configuration options. It basically tells Protractor the following −" }, { "code": null, "e": 35025, "s": 34987, "text": "Where to find the test or specs files" }, { "code": null, "e": 35047, "s": 35025, "text": "Which browser to pick" }, { "code": null, "e": 35078, "s": 35047, "text": "Which testing framework to use" }, { "code": null, "e": 35117, "s": 35078, "text": "Where to talk with the Selenium Server" }, { "code": null, "e": 35180, "s": 35117, "text": "The following is the simple script, config.js, having the test" }, { "code": null, "e": 35561, "s": 35180, "text": "// config.js\nexports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n\n // Spec patterns are relative to the current working directory when\n // protractor is called.\n specs: ['TestSpecification.js']," }, { "code": null, "e": 35659, "s": 35561, "text": "The code of above configuration file having three basic parameters, can be explained as follows −" }, { "code": null, "e": 35779, "s": 35659, "text": "This parameter is used to specify the name of the browser. It can be seen in the following code block of conf.js file −" }, { "code": null, "e": 35935, "s": 35779, "text": "exports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n},\n" }, { "code": null, "e": 36085, "s": 35935, "text": "As seen above, the name of the browser given here is ‘chrome’ which is by default browser for Protractor. We can also change the name of the browser." }, { "code": null, "e": 36217, "s": 36085, "text": "This parameter is used to specify the name of the testing framework. It can be seen in the following code block of config.js file −" }, { "code": null, "e": 36335, "s": 36217, "text": "exports.config = {\n directConnect: true,\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n" }, { "code": null, "e": 36379, "s": 36335, "text": "Here we are using ‘jasmine’ test framework." }, { "code": null, "e": 36515, "s": 36379, "text": "This parameter is used to specify the name of the source file declaration. It can be seen in the following code block of conf.js file −" }, { "code": null, "e": 36692, "s": 36515, "text": "exports.config = {\n directConnect: true,\n // Spec patterns are relative to the current working \n directory when protractor is called.\n specs: ['TsetSpecification.js'],\n" }, { "code": null, "e": 36888, "s": 36692, "text": "As seen above, the name of the source file declaration given here is ‘TestSpecification.js’. It is because, for this example we have created the specification file with name TestSpecification.js." }, { "code": null, "e": 37081, "s": 36888, "text": "As we have got basic understanding about the necessary files and their coding for running Protractor, let us try to run the example. We can follow the following steps to execute this example −" }, { "code": null, "e": 37118, "s": 37081, "text": "Step 1 − First, open command prompt." }, { "code": null, "e": 37155, "s": 37118, "text": "Step 1 − First, open command prompt." }, { "code": null, "e": 37271, "s": 37155, "text": "Step 2 − Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js." }, { "code": null, "e": 37387, "s": 37271, "text": "Step 2 − Next, we need go to the directory where we have saved our files namely config.js and TestSpecification.js." }, { "code": null, "e": 37474, "s": 37387, "text": "Step 3 − Now, execute the config.js file by running the command Protrcator config.js.\n" }, { "code": null, "e": 37561, "s": 37474, "text": "Step 3 − Now, execute the config.js file by running the command Protrcator config.js.\n" }, { "code": null, "e": 37646, "s": 37561, "text": "The screen shot shown below will explain the above steps for executing the example −" }, { "code": null, "e": 37707, "s": 37646, "text": "It is seen in the screen shot that the test has been passed." }, { "code": null, "e": 37907, "s": 37707, "text": "Now, suppose if we are testing non-angular websites and not putting the ignoreSynchronization tag to true then after executing the code we will get the error” Angular could not be found on the page”." }, { "code": null, "e": 37953, "s": 37907, "text": "It can be seen in the following screen shot −" }, { "code": null, "e": 38229, "s": 37953, "text": "Till now, we have discussed about the necessary files and their coding for running test cases. Protractor is also able to generate the report for test cases. For this purpose, it supports Jasmine. JunitXMLReporter can be used to generate test execution reports automatically." }, { "code": null, "e": 38319, "s": 38229, "text": "But before that, we need to install Jasmine reporter with the help of following command −" }, { "code": null, "e": 38353, "s": 38319, "text": "npm install -g jasmine-reporters\n" }, { "code": null, "e": 38492, "s": 38353, "text": "As you can see, -g option is used while installing Jasmine Reporters, it is because we have installed Protractor globally, with -g option." }, { "code": null, "e": 38617, "s": 38492, "text": "After successfully installing jasmine-reporters, we need to add the following code into our previously used config.js file −" }, { "code": null, "e": 38904, "s": 38617, "text": "onPrepare: function(){ //configure junit xml report\n\n var jasmineReporters = require('jasmine-reporters');\n jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({\n consolidateAll: true,\n filePrefix: 'guitest-xmloutput',\n savePath: 'test/reports'\n }));" }, { "code": null, "e": 38954, "s": 38904, "text": "Now, our new config.js file would be as follows −" }, { "code": null, "e": 39737, "s": 38954, "text": "// An example configuration file.\nexports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n\n // Spec patterns are relative to the current working directory when\n // protractor is called.\n specs: ['TestSpecification.js'],\n //framework: \"jasmine2\", //must set it if you use JUnitXmlReporter\n onPrepare: function(){ //configure junit xml report\n var jasmineReporters = require('jasmine-reporters');\n jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({\n consolidateAll: true,\n filePrefix: 'guitest-xmloutput',\n savePath: 'reports'\n }));\n },\n};" }, { "code": null, "e": 39971, "s": 39737, "text": "After running the above config file in the same way, we have run previously, it will generate an XML file containing the report under the root directory in reports folder. If the test got successful, the report will look like below −" }, { "code": null, "e": 40034, "s": 39971, "text": "But, if the test failed, the report will look as shown below −" }, { "code": null, "e": 40132, "s": 40034, "text": "This chapter lets you understand various core APIs that are key to the functioning of protractor." }, { "code": null, "e": 40290, "s": 40132, "text": "Protractor provides us a wide range of APIs which are very important in order to perform the following actions for getting the current state of the website −" }, { "code": null, "e": 40353, "s": 40290, "text": "Getting the DOM elements of the web page we are going to test." }, { "code": null, "e": 40388, "s": 40353, "text": "Interacting with the DOM elements." }, { "code": null, "e": 40415, "s": 40388, "text": "Assigning actions to them." }, { "code": null, "e": 40444, "s": 40415, "text": "Sharing information to them." }, { "code": null, "e": 40524, "s": 40444, "text": "To perform the above tasks, it is very important to understand Protractor APIs." }, { "code": null, "e": 40671, "s": 40524, "text": "As we know that Protractor is a wrapper around Selenium-WebDriver which is the WebDriver bindings for Node.js. Protractor has the following APIs −" }, { "code": null, "e": 40863, "s": 40671, "text": "It is a wrapper around an instance of WebDriver which is used to handle browser level commands such as navigation, page-wide information etc. For example, the browser.get method loads a page." }, { "code": null, "e": 41012, "s": 40863, "text": "It is used to search and interact with DOM element on the page we are testing. For this purpose, it requires one parameter for locating the element." }, { "code": null, "e": 41184, "s": 41012, "text": "It is a collection of element locator strategies. The elements, for example, can be found by CSS selector, by ID or by any other attribute they are bound to with ng-model." }, { "code": null, "e": 41262, "s": 41184, "text": "Next, we are going to discuss in detail about these APIs and their functions." }, { "code": null, "e": 41410, "s": 41262, "text": "As discussed above, it is a wrapper around an instance of WebDriver for handling browser level commands. It performs various functions as follows −" }, { "code": null, "e": 41465, "s": 41410, "text": "The functions of ProtractorBrowser API are as follows−" }, { "code": null, "e": 41488, "s": 41465, "text": "browser.angularAppRoot" }, { "code": null, "e": 41723, "s": 41488, "text": "This function of Browser API sets the CSS selector for an element on which we are going to find Angular. Usually, this function is in ‘body’, but in case if our ng-app, it is on a sub-section of the page; it may be a sub-element also." }, { "code": null, "e": 41753, "s": 41723, "text": "browser.waitForAngularEnabled" }, { "code": null, "e": 42098, "s": 41753, "text": "This function of Browser API can be set to true or false. As the name suggests, if this function is set for false then Protractor will not wait for Angular $http and $timeout tasks to complete before interacting with the browser. We can also read the current state without changing it by calling waitForAngularEnabled() without passing a value." }, { "code": null, "e": 42125, "s": 42098, "text": "browser.getProcessedConfig" }, { "code": null, "e": 42285, "s": 42125, "text": "With the help of this browser APIs function we can get the processed configuration object, including specification & capabilities, that is currently being run." }, { "code": null, "e": 42315, "s": 42285, "text": "browser.forkNewDriverInstance" }, { "code": null, "e": 42519, "s": 42315, "text": "As the name suggests this function will fork another instance of browser to be used in interactive tests. It can be run with control flow enabled and disabled. Example is given below for both the cases −" }, { "code": null, "e": 42529, "s": 42519, "text": "Example 1" }, { "code": null, "e": 42597, "s": 42529, "text": "Running browser.forkNewDriverInstance() with control flow enabled −" }, { "code": null, "e": 42661, "s": 42597, "text": "var fork = browser.forkNewDriverInstance();\nfork.get(‘page1’);\n" }, { "code": null, "e": 42671, "s": 42661, "text": "Example 2" }, { "code": null, "e": 42740, "s": 42671, "text": "Running browser.forkNewDriverInstance() with control flow disabled −" }, { "code": null, "e": 42824, "s": 42740, "text": "var fork = await browser.forkNewDriverInstance().ready;\nawait forked.get(‘page1’);\n" }, { "code": null, "e": 42840, "s": 42824, "text": "browser.restart" }, { "code": null, "e": 43040, "s": 42840, "text": "As the name suggests, it will restart the browser by closing browser instance and creating new one. It can also run with control flow enabled and disabled. Example is given below for both the cases −" }, { "code": null, "e": 43106, "s": 43040, "text": "Example 1 − Running browser.restart() with control flow enabled −" }, { "code": null, "e": 43170, "s": 43106, "text": "browser.get(‘page1’);\nbrowser.restart();\nbrowser.get(‘page2’);\n" }, { "code": null, "e": 43251, "s": 43170, "text": "Example 2 − Running browser.forkNewDriverInstance() with control flow disabled −" }, { "code": null, "e": 43333, "s": 43251, "text": "await browser.get(‘page1’);\nawait browser.restart();\nawait browser.get(‘page2’);\n" }, { "code": null, "e": 43572, "s": 43333, "text": "It is similar to browser.restart() function. The only difference is that it returns the new browser instance directly rather than returning a promise resolving to the new browser instance. It can only run when the control flow is enabled." }, { "code": null, "e": 43641, "s": 43572, "text": "Example − Running browser.restartSync() with control flow enabled −" }, { "code": null, "e": 43709, "s": 43641, "text": "browser.get(‘page1’);\nbrowser.restartSync();\nbrowser.get(‘page2’);\n" }, { "code": null, "e": 43740, "s": 43709, "text": "browser.useAllAngular2AppRoots" }, { "code": null, "e": 43914, "s": 43740, "text": "As the name suggests, it is compatible with Angular2 only. It will search through all the angular apps available on the page while finding elements or waiting for stability." }, { "code": null, "e": 43937, "s": 43914, "text": "browser.waitForAngular" }, { "code": null, "e": 44098, "s": 43937, "text": "This browser API function instructs the WebDriver to wait until Angular has finished rendering and has no outstanding $http or $timeout calls before continuing." }, { "code": null, "e": 44118, "s": 44098, "text": "browser.findElement" }, { "code": null, "e": 44234, "s": 44118, "text": "As the name suggests, this browser API function waits for Angular to finish rendering before searching for element." }, { "code": null, "e": 44259, "s": 44234, "text": "browser.isElementPresent" }, { "code": null, "e": 44375, "s": 44259, "text": "As the name suggests, this browser API function will test for the for the element to be present on the page or not." }, { "code": null, "e": 44397, "s": 44375, "text": "browser.addMockModule" }, { "code": null, "e": 44485, "s": 44397, "text": "It will add a module to load before Angular every time Protractor.get method is called." }, { "code": null, "e": 44493, "s": 44485, "text": "Example" }, { "code": null, "e": 44598, "s": 44493, "text": "browser.addMockModule('modName', function() {\n angular.module('modName', []).value('foo', 'bar');\n});\n" }, { "code": null, "e": 44623, "s": 44598, "text": "browser.clearMockModules" }, { "code": null, "e": 44704, "s": 44623, "text": "unlike browser.addMockModule, it will clear the list of registered mock modules." }, { "code": null, "e": 44729, "s": 44704, "text": "browser.removeMockModule" }, { "code": null, "e": 44837, "s": 44729, "text": "As the name suggests, it will remove a register mock modules. Example: browser.removeMockModule(‘modName’);" }, { "code": null, "e": 44870, "s": 44837, "text": "browser.getRegisteredMockModules" }, { "code": null, "e": 44956, "s": 44870, "text": "Opposite to browser.clearMockModule, it will get the list of registered mock modules." }, { "code": null, "e": 44968, "s": 44956, "text": "browser.get" }, { "code": null, "e": 45110, "s": 44968, "text": "We can use browser.get() to navigate the browser to a particular web address and load the mock modules for that page before the Angular load." }, { "code": null, "e": 45118, "s": 45110, "text": "Example" }, { "code": null, "e": 45256, "s": 45118, "text": "browser.get(url);\nbrowser.get('http://localhost:3000'); \n// This will navigate to the localhost:3000 and will load mock module if needed\n" }, { "code": null, "e": 45272, "s": 45256, "text": "browser.refresh" }, { "code": null, "e": 45367, "s": 45272, "text": "As the name suggests, this will reload the current page and loads mock modules before Angular." }, { "code": null, "e": 45384, "s": 45367, "text": "browser.navigate" }, { "code": null, "e": 45549, "s": 45384, "text": "As the name suggests, it is used to mix navigation methods back into the navigation object so that they are invoked as before. Example: driver.navigate().refresh()." }, { "code": null, "e": 45569, "s": 45549, "text": "browser.setLocation" }, { "code": null, "e": 45631, "s": 45569, "text": "It is use to browse to another page using in-page navigation." }, { "code": null, "e": 45639, "s": 45631, "text": "Example" }, { "code": null, "e": 45745, "s": 45639, "text": "browser.get('url/ABC');\nbrowser.setLocation('DEF');\nexpect(browser.getCurrentUrl())\n .toBe('url/DEF');\n" }, { "code": null, "e": 45784, "s": 45745, "text": "It will navigate from ABC to DEF page." }, { "code": null, "e": 45801, "s": 45784, "text": "browser.debugger" }, { "code": null, "e": 46033, "s": 45801, "text": "As the name suggests, this must be used with protractor debug. This function basically adds a task to the control flow to pause the test and inject helper functions into the browser so that debugging can be done in browser console." }, { "code": null, "e": 46047, "s": 46033, "text": "browser.pause" }, { "code": null, "e": 46198, "s": 46047, "text": "It is used for debugging WebDriver tests. We can use browser.pause() in our test to enter the protractor debugger from that point in the control flow." }, { "code": null, "e": 46206, "s": 46198, "text": "Example" }, { "code": null, "e": 46339, "s": 46206, "text": "element(by.id('foo')).click();\nbrowser.pause();\n// Execution will stop before the next click action.\nelement(by.id('bar')).click();\n" }, { "code": null, "e": 46366, "s": 46339, "text": "browser.controlFlowEnabled" }, { "code": null, "e": 46434, "s": 46366, "text": "It is used to determine whether the control flow is enabled or not." }, { "code": null, "e": 46499, "s": 46434, "text": "In this chapter, let us learn some more core APIs of Protractor." }, { "code": null, "e": 46619, "s": 46499, "text": "Element is one of the global functions exposed by protractor. This function takes a locater and returns the following −" }, { "code": null, "e": 46684, "s": 46619, "text": "ElementFinder, that finds a single element based on the locator." }, { "code": null, "e": 46758, "s": 46684, "text": "ElementArrayFinder, that finds an array of elements based on the locator." }, { "code": null, "e": 46818, "s": 46758, "text": "Both the above support chaining methods as discussed below." }, { "code": null, "e": 46875, "s": 46818, "text": "The Followings are the functions of ElementArrayFinder −" }, { "code": null, "e": 46902, "s": 46875, "text": "element.all(locator).clone" }, { "code": null, "e": 47019, "s": 46902, "text": "As the name suggests, this function will create a shallow copy of the array of the elements i.e. ElementArrayFinder." }, { "code": null, "e": 47053, "s": 47019, "text": "element.all(locator).all(locator)" }, { "code": null, "e": 47235, "s": 47053, "text": "This function basically returns a new ElementArrayFinder which could be empty or contain the children elements. It can be used for selecting multiple elements as an array as follows" }, { "code": null, "e": 47243, "s": 47235, "text": "Example" }, { "code": null, "e": 47403, "s": 47243, "text": "element.all(locator).all(locator)\nelementArr.all(by.css(‘.childselector’));\n// it will return another ElementFindArray as child element based on child locator." }, { "code": null, "e": 47441, "s": 47403, "text": "element.all(locator).filter(filterFn)" }, { "code": null, "e": 47741, "s": 47441, "text": "As the name suggests, after applying filter function to each element within ElementArrayFinder, it returns a new ElementArrayFinder with all elements that pass the filter function. It is basically having two arguments, first is ElementFinder and second is index. It can also be used in page objects." }, { "code": null, "e": 47749, "s": 47741, "text": "Example" }, { "code": null, "e": 47754, "s": 47749, "text": "View" }, { "code": null, "e": 47880, "s": 47754, "text": "<ul class = \"items\">\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n</ul>" }, { "code": null, "e": 47885, "s": 47880, "text": "Code" }, { "code": null, "e": 48054, "s": 47885, "text": "element.all(by.css('.items li')).filter(function(elem, index) {\n return elem.getText().then(function(text) {\n return text === 'Third';\n });\n}).first().click();" }, { "code": null, "e": 48086, "s": 48054, "text": "element.all(locator).get(index)" }, { "code": null, "e": 48237, "s": 48086, "text": "With the help of this, we can get an element within the ElementArrayFinder by index. Note that the index starts at 0 and negative indices are wrapped." }, { "code": null, "e": 48245, "s": 48237, "text": "Example" }, { "code": null, "e": 48250, "s": 48245, "text": "View" }, { "code": null, "e": 48332, "s": 48250, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 48337, "s": 48332, "text": "Code" }, { "code": null, "e": 48473, "s": 48337, "text": "let list = element.all(by.css('.items li'));\nexpect(list.get(0).getText()).toBe('First');\nexpect(list.get(1).getText()).toBe('Second');" }, { "code": null, "e": 48502, "s": 48473, "text": "element.all(locator).first()" }, { "code": null, "e": 48625, "s": 48502, "text": "As the name suggests, this will get the first element for ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 48633, "s": 48625, "text": "Example" }, { "code": null, "e": 48638, "s": 48633, "text": "View" }, { "code": null, "e": 48721, "s": 48638, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>\n" }, { "code": null, "e": 48726, "s": 48721, "text": "Code" }, { "code": null, "e": 48819, "s": 48726, "text": "let first = element.all(by.css('.items li')).first();\nexpect(first.getText()).toBe('First');" }, { "code": null, "e": 48847, "s": 48819, "text": "element.all(locator).last()" }, { "code": null, "e": 48964, "s": 48847, "text": "As name suggest, this will get the last element for ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 48972, "s": 48964, "text": "Example" }, { "code": null, "e": 48977, "s": 48972, "text": "View" }, { "code": null, "e": 49059, "s": 48977, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 49064, "s": 49059, "text": "Code" }, { "code": null, "e": 49155, "s": 49064, "text": "let first = element.all(by.css('.items li')).last();\nexpect(last.getText()).toBe('Third');" }, { "code": null, "e": 49190, "s": 49155, "text": "element.all(locator).all(selector)" }, { "code": null, "e": 49279, "s": 49190, "text": "It is used to find an array of elements within a parent when calls to $$ may be chained." }, { "code": null, "e": 49287, "s": 49279, "text": "Example" }, { "code": null, "e": 49292, "s": 49287, "text": "View" }, { "code": null, "e": 49447, "s": 49292, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 49452, "s": 49447, "text": "Code" }, { "code": null, "e": 49501, "s": 49452, "text": "let items = element(by.css('.parent')).$$('li');" }, { "code": null, "e": 49530, "s": 49501, "text": "element.all(locator).count()" }, { "code": null, "e": 49671, "s": 49530, "text": "As the name suggests, this will count the number of elements represented by ElementArrayFinder. It will not retrieve the underlying element." }, { "code": null, "e": 49679, "s": 49671, "text": "Example" }, { "code": null, "e": 49684, "s": 49679, "text": "View" }, { "code": null, "e": 49766, "s": 49684, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 49771, "s": 49766, "text": "Code" }, { "code": null, "e": 49846, "s": 49771, "text": "let list = element.all(by.css('.items li'));\nexpect(list.count()).toBe(3);" }, { "code": null, "e": 49879, "s": 49846, "text": "element.all(locator).isPresent()" }, { "code": null, "e": 50035, "s": 49879, "text": "It will match the elements with the finder. It can return true or false. True, if there are any elements present that match the finder and False otherwise." }, { "code": null, "e": 50043, "s": 50035, "text": "Example" }, { "code": null, "e": 50088, "s": 50043, "text": "expect($('.item').isPresent()).toBeTruthy();" }, { "code": null, "e": 50117, "s": 50088, "text": "element.all(locator).locator" }, { "code": null, "e": 50181, "s": 50117, "text": "As the name suggests, it will return the most relevant locator." }, { "code": null, "e": 50189, "s": 50181, "text": "Example" }, { "code": null, "e": 50373, "s": 50189, "text": "$('#ID1').locator();\n// returns by.css('#ID1')\n$('#ID1').$('#ID2').locator();\n// returns by.css('#ID2')\n$$('#ID1').filter(filterFn).get(0).click().locator();\n// returns by.css('#ID1')" }, { "code": null, "e": 50413, "s": 50373, "text": "element.all(locator).then(thenFunction)" }, { "code": null, "e": 50482, "s": 50413, "text": "It will retrieve the elements represented by the ElementArrayFinder." }, { "code": null, "e": 50490, "s": 50482, "text": "Example" }, { "code": null, "e": 50495, "s": 50490, "text": "View" }, { "code": null, "e": 50577, "s": 50495, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 50582, "s": 50577, "text": "Code" }, { "code": null, "e": 50674, "s": 50582, "text": "element.all(by.css('.items li')).then(function(arr) {\n expect(arr.length).toEqual(3);\n});" }, { "code": null, "e": 50714, "s": 50674, "text": "element.all(locator).each(eachFunction)" }, { "code": null, "e": 50829, "s": 50714, "text": "As the name suggests, it will call the input function on each ElementFinder represented by the ElementArrayFinder." }, { "code": null, "e": 50837, "s": 50829, "text": "Example" }, { "code": null, "e": 50842, "s": 50837, "text": "View" }, { "code": null, "e": 50924, "s": 50842, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 50929, "s": 50924, "text": "Code" }, { "code": null, "e": 51132, "s": 50929, "text": "element.all(by.css('.items li')).each(function(element, index) {\n // It will print First 0, Second 1 and Third 2.\n element.getText().then(function (text) {\n console.log(index, text);\n });\n});" }, { "code": null, "e": 51170, "s": 51132, "text": "element.all(locator).map(mapFunction)" }, { "code": null, "e": 51355, "s": 51170, "text": "As name suggest, it will apply a map function on each element within the ElementArrayFinder. It is having two arguments. First would be the ElementFinder and second would be the index." }, { "code": null, "e": 51363, "s": 51355, "text": "Example" }, { "code": null, "e": 51368, "s": 51363, "text": "View" }, { "code": null, "e": 51450, "s": 51368, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>" }, { "code": null, "e": 51455, "s": 51450, "text": "Code" }, { "code": null, "e": 51797, "s": 51455, "text": "let items = element.all(by.css('.items li')).map(function(elm, index) {\n return {\n index: index,\n text: elm.getText(),\n class: elm.getAttribute('class')\n };\n});\nexpect(items).toEqual([\n {index: 0, text: 'First', class: 'one'},\n {index: 1, text: 'Second', class: 'two'},\n {index: 2, text: 'Third', class: 'three'}\n]);" }, { "code": null, "e": 51835, "s": 51797, "text": "element.all(locator).reduce(reduceFn)" }, { "code": null, "e": 52016, "s": 51835, "text": "As the name suggests, it will apply a reduce function against an accumulator and every element found using the locator. This function will reduce every element into a single value." }, { "code": null, "e": 52024, "s": 52016, "text": "Example" }, { "code": null, "e": 52029, "s": 52024, "text": "View" }, { "code": null, "e": 52112, "s": 52029, "text": "<ul class = \"items\">\n <li>First</li>\n <li>Second</li>\n <li>Third</li>\n</ul>\n" }, { "code": null, "e": 52117, "s": 52112, "text": "Code" }, { "code": null, "e": 52331, "s": 52117, "text": "let value = element.all(by.css('.items li')).reduce(function(acc, elem) {\n return elem.getText().then(function(text) {\n return acc + text + ' ';\n });\n}, '');\n\nexpect(value).toEqual('First Second Third ');" }, { "code": null, "e": 52361, "s": 52331, "text": "element.all(locator).evaluate" }, { "code": null, "e": 52480, "s": 52361, "text": "As the name suggests, it will evaluate the input whether it is in the scope of the current underlying elements or not." }, { "code": null, "e": 52488, "s": 52480, "text": "Example" }, { "code": null, "e": 52493, "s": 52488, "text": "View" }, { "code": null, "e": 52540, "s": 52493, "text": "<span class = \"foo\">{{letiableInScope}}</span>" }, { "code": null, "e": 52545, "s": 52540, "text": "Code" }, { "code": null, "e": 52615, "s": 52545, "text": "let value = \nelement.all(by.css('.foo')).evaluate('letiableInScope');" }, { "code": null, "e": 52652, "s": 52615, "text": "element.all(locator).allowAnimations" }, { "code": null, "e": 52763, "s": 52652, "text": "As name suggest, it will determine whether the animation is allowed on the current underlying elements or not." }, { "code": null, "e": 52771, "s": 52763, "text": "Example" }, { "code": null, "e": 52819, "s": 52771, "text": "element(by.css('body')).allowAnimations(false);" }, { "code": null, "e": 52880, "s": 52819, "text": "Chaining functions of ElementFinder and their descriptions −" }, { "code": null, "e": 52903, "s": 52880, "text": "element(locator).clone" }, { "code": null, "e": 52988, "s": 52903, "text": "As the name suggests, this function will create a shallow copy of the ElementFinder." }, { "code": null, "e": 53021, "s": 52988, "text": "element(locator).getWebElement()" }, { "code": null, "e": 53153, "s": 53021, "text": "It will return the WebElement represented by this ElementFinder and a WebDriver error will be thrown if the element does not exist." }, { "code": null, "e": 53161, "s": 53153, "text": "Example" }, { "code": null, "e": 53166, "s": 53161, "text": "View" }, { "code": null, "e": 53207, "s": 53166, "text": "<div class=\"parent\">\n some text\n</div>" }, { "code": null, "e": 53212, "s": 53207, "text": "Code" }, { "code": null, "e": 53427, "s": 53212, "text": "// All the four following expressions are equivalent.\n$('.parent').getWebElement();\nelement(by.css('.parent')).getWebElement();\nbrowser.driver.findElement(by.css('.parent'));\nbrowser.findElement(by.css('.parent'));" }, { "code": null, "e": 53457, "s": 53427, "text": "element(locator).all(locator)" }, { "code": null, "e": 53508, "s": 53457, "text": "It will find an array of elements within a parent." }, { "code": null, "e": 53516, "s": 53508, "text": "Example" }, { "code": null, "e": 53521, "s": 53516, "text": "View" }, { "code": null, "e": 53676, "s": 53521, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 53681, "s": 53676, "text": "Code" }, { "code": null, "e": 53743, "s": 53681, "text": "let items = element(by.css('.parent')).all(by.tagName('li'));" }, { "code": null, "e": 53777, "s": 53743, "text": "element(locator).element(locator)" }, { "code": null, "e": 53816, "s": 53777, "text": "It will find elements within a parent." }, { "code": null, "e": 53824, "s": 53816, "text": "Example" }, { "code": null, "e": 53829, "s": 53824, "text": "View" }, { "code": null, "e": 53946, "s": 53829, "text": "<div class = \"parent\">\n <div class = \"child\">\n Child text\n <div>{{person.phone}}</div>\n </div>\n</div>\n" }, { "code": null, "e": 53951, "s": 53946, "text": "Code" }, { "code": null, "e": 54288, "s": 53951, "text": "// Calls Chain 2 element.\nlet child = element(by.css('.parent')).\n element(by.css('.child'));\nexpect(child.getText()).toBe('Child text\\n981-000-568');\n\n// Calls Chain 3 element.\nlet triple = element(by.css('.parent')).\n element(by.css('.child')).\n element(by.binding('person.phone'));\nexpect(triple.getText()).toBe('981-000-568');" }, { "code": null, "e": 54319, "s": 54288, "text": "element(locator).all(selector)" }, { "code": null, "e": 54402, "s": 54319, "text": "It will find an array of elements within a parent when calls to $$ may be chained." }, { "code": null, "e": 54410, "s": 54402, "text": "Example" }, { "code": null, "e": 54415, "s": 54410, "text": "View" }, { "code": null, "e": 54570, "s": 54415, "text": "<div class = \"parent\">\n <ul>\n <li class = \"one\">First</li>\n <li class = \"two\">Second</li>\n <li class = \"three\">Third</li>\n </ul>\n</div>" }, { "code": null, "e": 54575, "s": 54570, "text": "Code" }, { "code": null, "e": 54625, "s": 54575, "text": "let items = element(by.css('.parent')).$$('li'));" }, { "code": null, "e": 54653, "s": 54625, "text": "element(locator).$(locator)" }, { "code": null, "e": 54723, "s": 54653, "text": "It will find elements within a parent when calls to $ may be chained." }, { "code": null, "e": 54731, "s": 54723, "text": "Example" }, { "code": null, "e": 54736, "s": 54731, "text": "View" }, { "code": null, "e": 54851, "s": 54736, "text": "<div class = \"parent\">\n <div class = \"child\">\n Child text\n <div>{{person.phone}}</div>\n </div>\n</div>" }, { "code": null, "e": 54856, "s": 54851, "text": "Code" }, { "code": null, "e": 55167, "s": 54856, "text": "// Calls Chain 2 element.\nlet child = element(by.css('.parent')).\n $('.child'));\nexpect(child.getText()).toBe('Child text\\n981-000-568');\n\n// Calls Chain 3 element.\nlet triple = element(by.css('.parent')).\n $('.child')).\n element(by.binding('person.phone'));\nexpect(triple.getText()).toBe('981-000-568');" }, { "code": null, "e": 55196, "s": 55167, "text": "element(locator).isPresent()" }, { "code": null, "e": 55263, "s": 55196, "text": "It will determine whether the element is presented on page or not." }, { "code": null, "e": 55271, "s": 55263, "text": "Example" }, { "code": null, "e": 55276, "s": 55271, "text": "View" }, { "code": null, "e": 55305, "s": 55276, "text": "<span>{{person.name}}</span>" }, { "code": null, "e": 55310, "s": 55305, "text": "Code" }, { "code": null, "e": 55536, "s": 55310, "text": "expect(element(by.binding('person.name')).isPresent()).toBe(true);\n// will check for the existence of element\n\nexpect(element(by.binding('notPresent')).isPresent()).toBe(false); \n// will check for the non-existence of element" }, { "code": null, "e": 55572, "s": 55536, "text": "element(locator).isElementPresent()" }, { "code": null, "e": 55754, "s": 55572, "text": "It is same as element(locator).isPresent(). The only difference is that it will check whether the element identified by sublocator is present rather than the current element finder." }, { "code": null, "e": 55784, "s": 55754, "text": "element.all(locator).evaluate" }, { "code": null, "e": 55903, "s": 55784, "text": "As the name suggests, it will evaluate the input whether it is on the scope of the current underlying elements or not." }, { "code": null, "e": 55911, "s": 55903, "text": "Example" }, { "code": null, "e": 55916, "s": 55911, "text": "View" }, { "code": null, "e": 55961, "s": 55916, "text": "<span id = \"foo\">{{letiableInScope}}</span>\n" }, { "code": null, "e": 55966, "s": 55961, "text": "Code" }, { "code": null, "e": 56030, "s": 55966, "text": "let value = element(by.id('.foo')).evaluate('letiableInScope');" }, { "code": null, "e": 56063, "s": 56030, "text": "element(locator).allowAnimations" }, { "code": null, "e": 56179, "s": 56063, "text": "As the name suggests, it will determine whether the animation is allowed on the current underlying elements or not." }, { "code": null, "e": 56187, "s": 56179, "text": "Example" }, { "code": null, "e": 56236, "s": 56187, "text": "element(by.css('body')).allowAnimations(false);\n" }, { "code": null, "e": 56260, "s": 56236, "text": "element(locator).equals" }, { "code": null, "e": 56323, "s": 56260, "text": "As the name suggests, it will compare an element for equality." }, { "code": null, "e": 56468, "s": 56323, "text": "It is basically a collection of element locator strategies that provides ways of finding elements in Angular applications by binding, model etc." }, { "code": null, "e": 56501, "s": 56468, "text": "Functions and their descriptions" }, { "code": null, "e": 56558, "s": 56501, "text": "The functions of ProtractorLocators API are as follows −" }, { "code": null, "e": 56601, "s": 56558, "text": "by.addLocator(locatorName,fuctionOrScript)" }, { "code": null, "e": 56718, "s": 56601, "text": "It will add a locator to this instance of ProtrcatorBy which further can be used with element(by.locatorName(args))." }, { "code": null, "e": 56726, "s": 56718, "text": "Example" }, { "code": null, "e": 56731, "s": 56726, "text": "View" }, { "code": null, "e": 56778, "s": 56731, "text": "<button ng-click = \"doAddition()\">Go!</button>" }, { "code": null, "e": 56783, "s": 56778, "text": "Code" }, { "code": null, "e": 57218, "s": 56783, "text": "// Adding the custom locator.\nby.addLocator('buttonTextSimple',\n function(buttonText, opt_parentElement, opt_rootSelector) {\n\n var using = opt_parentElement || document,\n buttons = using.querySelectorAll('button');\n\n return Array.prototype.filter.call(buttons, function(button) {\n return button.textContent === buttonText;\n });\n});\nelement(by.buttonTextSimple('Go!')).click();// Using the custom locator." }, { "code": null, "e": 57229, "s": 57218, "text": "by.binding" }, { "code": null, "e": 57411, "s": 57229, "text": "As the name suggests, it will find an element by text binding. A partial match will be done so that any elements bound to the variables containing the input string will be returned." }, { "code": null, "e": 57419, "s": 57411, "text": "Example" }, { "code": null, "e": 57424, "s": 57419, "text": "View" }, { "code": null, "e": 57492, "s": 57424, "text": "<span>{{person.name}}</span>\n<span ng-bind = \"person.email\"></span>" }, { "code": null, "e": 57497, "s": 57492, "text": "Code" }, { "code": null, "e": 57677, "s": 57497, "text": "var span1 = element(by.binding('person.name'));\nexpect(span1.getText()).toBe('Foo');\n\nvar span2 = element(by.binding('person.email'));\nexpect(span2.getText()).toBe('[email protected]');" }, { "code": null, "e": 57693, "s": 57677, "text": "by.exactbinding" }, { "code": null, "e": 57757, "s": 57693, "text": "As the name suggests, it will find an element by exact binding." }, { "code": null, "e": 57765, "s": 57757, "text": "Example" }, { "code": null, "e": 57770, "s": 57765, "text": "View" }, { "code": null, "e": 57890, "s": 57770, "text": "<spangt;{{ person.name }}</spangt;\n<span ng-bind = \"person-email\"gt;</spangt;\n<spangt;{{person_phone|uppercase}}</span>" }, { "code": null, "e": 57895, "s": 57890, "text": "Code" }, { "code": null, "e": 58331, "s": 57895, "text": "expect(element(by.exactBinding('person.name')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person-email')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person')).isPresent()).toBe(false);\nexpect(element(by.exactBinding('person_phone')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true);\nexpect(element(by.exactBinding('phone')).isPresent()).toBe(false);" }, { "code": null, "e": 58351, "s": 58331, "text": "by.model(modelName)" }, { "code": null, "e": 58421, "s": 58351, "text": "As the name suggests, it will find an element by ng-model expression." }, { "code": null, "e": 58429, "s": 58421, "text": "Example" }, { "code": null, "e": 58434, "s": 58429, "text": "View" }, { "code": null, "e": 58481, "s": 58434, "text": "<input type = \"text\" ng-model = \"person.name\">" }, { "code": null, "e": 58486, "s": 58481, "text": "Code" }, { "code": null, "e": 58607, "s": 58486, "text": "var input = element(by.model('person.name'));\ninput.sendKeys('123');\nexpect(input.getAttribute('value')).toBe('Foo123');" }, { "code": null, "e": 58621, "s": 58607, "text": "by.buttonText" }, { "code": null, "e": 58674, "s": 58621, "text": "As the name suggests, it will find a button by text." }, { "code": null, "e": 58682, "s": 58674, "text": "Example" }, { "code": null, "e": 58687, "s": 58682, "text": "View" }, { "code": null, "e": 58710, "s": 58687, "text": "<button>Save</button>\n" }, { "code": null, "e": 58715, "s": 58710, "text": "Code" }, { "code": null, "e": 58747, "s": 58715, "text": "element(by.buttonText('Save'));" }, { "code": null, "e": 58768, "s": 58747, "text": "by.partialButtonText" }, { "code": null, "e": 58829, "s": 58768, "text": "As the name suggests, it will find a button by partial text." }, { "code": null, "e": 58837, "s": 58829, "text": "Example" }, { "code": null, "e": 58842, "s": 58837, "text": "View" }, { "code": null, "e": 58872, "s": 58842, "text": "<button>Save my file</button>" }, { "code": null, "e": 58877, "s": 58872, "text": "Code" }, { "code": null, "e": 58916, "s": 58877, "text": "element(by.partialButtonText('Save'));" }, { "code": null, "e": 58928, "s": 58916, "text": "by.repeater" }, { "code": null, "e": 58995, "s": 58928, "text": "As the name suggests, it will find an element inside an ng-repeat." }, { "code": null, "e": 59003, "s": 58995, "text": "Example" }, { "code": null, "e": 59008, "s": 59003, "text": "View" }, { "code": null, "e": 59296, "s": 59008, "text": "<div ng-repeat = \"cat in pets\">\n <span>{{cat.name}}</span>\n <span>{{cat.age}}</span>\n<</div>\n<div class = \"book-img\" ng-repeat-start=\"book in library\">\n <span>{{$index}}</span>\n</div>\n<div class = \"book-info\" ng-repeat-end>\n <h4>{{book.name}}</h4>\n <p>{{book.blurb}}</p>\n</div>" }, { "code": null, "e": 59301, "s": 59296, "text": "Code" }, { "code": null, "e": 59547, "s": 59301, "text": "var secondCat = element(by.repeater('cat in \npets').row(1)); // It will return the DIV for the second cat.\nvar firstCatName = element(by.repeater('cat in pets').\n row(0).column('cat.name')); // It will return the SPAN for the first cat's name." }, { "code": null, "e": 59564, "s": 59547, "text": "by.exactRepeater" }, { "code": null, "e": 59629, "s": 59564, "text": "As the name suggests, it will find an element by exact repeater." }, { "code": null, "e": 59637, "s": 59629, "text": "Example" }, { "code": null, "e": 59642, "s": 59637, "text": "View" }, { "code": null, "e": 59745, "s": 59642, "text": "<li ng-repeat = \"person in peopleWithRedHair\"></li>\n<li ng-repeat = \"car in cars | orderBy:year\"></li>" }, { "code": null, "e": 59750, "s": 59745, "text": "Code" }, { "code": null, "e": 59995, "s": 59750, "text": "expect(element(by.exactRepeater('person in\npeopleWithRedHair')).isPresent())\n .toBe(true);\nexpect(element(by.exactRepeater('person in\npeople')).isPresent()).toBe(false);\nexpect(element(by.exactRepeater('car in cars')).isPresent()).toBe(true);" }, { "code": null, "e": 60016, "s": 59995, "text": "by.cssContainingText" }, { "code": null, "e": 60092, "s": 60016, "text": "As name suggest, it will find the elements, containing exact string, by CSS" }, { "code": null, "e": 60100, "s": 60092, "text": "Example" }, { "code": null, "e": 60105, "s": 60100, "text": "View" }, { "code": null, "e": 60170, "s": 60105, "text": "<ul>\n<li class = \"pet\">Dog</li>\n<li class = \"pet\">Cat</li>\n</ul>" }, { "code": null, "e": 60175, "s": 60170, "text": "Code" }, { "code": null, "e": 60291, "s": 60175, "text": "var dog = element(by.cssContainingText('.pet', 'Dog')); \n// It will return the li for the dog, but not for the cat." }, { "code": null, "e": 60321, "s": 60291, "text": "by.options(optionsDescriptor)" }, { "code": null, "e": 60393, "s": 60321, "text": "As the name suggests, it will find an element by ng-options expression." }, { "code": null, "e": 60401, "s": 60393, "text": "Example" }, { "code": null, "e": 60406, "s": 60401, "text": "View" }, { "code": null, "e": 60573, "s": 60406, "text": "<select ng-model = \"color\" ng-options = \"c for c in colors\">\n <option value = \"0\" selected = \"selected\">red</option>\n <option value = \"1\">green</option>\n</select>" }, { "code": null, "e": 60578, "s": 60573, "text": "Code" }, { "code": null, "e": 60764, "s": 60578, "text": "var allOptions = element.all(by.options('c for c in colors'));\nexpect(allOptions.count()).toEqual(2);\nvar firstOption = allOptions.first();\nexpect(firstOption.getText()).toEqual('red');" }, { "code": null, "e": 60785, "s": 60764, "text": "by.deepCSS(selector)" }, { "code": null, "e": 60865, "s": 60785, "text": "As name suggest, it will find an element by CSS selector within the shadow DOM." }, { "code": null, "e": 60873, "s": 60865, "text": "Example" }, { "code": null, "e": 60878, "s": 60873, "text": "View" }, { "code": null, "e": 61045, "s": 60878, "text": "<div>\n <span id = \"outerspan\">\n <\"shadow tree\">\n <span id = \"span1\"></span>\n <\"shadow tree\">\n <span id = \"span2\"></span>\n </>\n </>\n</div>" }, { "code": null, "e": 61050, "s": 61045, "text": "Code" }, { "code": null, "e": 61129, "s": 61050, "text": "var spans = element.all(by.deepCss('span'));\nexpect(spans.count()).toEqual(3);" }, { "code": null, "e": 61195, "s": 61129, "text": "This chapter discusses in detail about the objects in Protractor." }, { "code": null, "e": 61608, "s": 61195, "text": "Page object is a design pattern which has become popular for writing e2e tests in order to enhance the test maintenance and reducing the code duplication. It may be defined as an object-oriented class serving as an interface to a page of your AUT (application under test). But, before diving deep into page objects, we must have to understand the challenges with automated UI testing and the ways to handle them." }, { "code": null, "e": 61674, "s": 61608, "text": "Followings are some common challenges with automates UI testing −" }, { "code": null, "e": 61883, "s": 61674, "text": "The very common issues while working with UI testing is the changes happens in UI. For example, it happens most of the time that buttons or textboxes etc. usually got change and creates issues for UI testing." }, { "code": null, "e": 62015, "s": 61883, "text": "Another issue with UI testing is the lack of DSL support. With this issue, it becomes very hard to understand what is being tested." }, { "code": null, "e": 62174, "s": 62015, "text": "The next common problem in UI testing is that there is lots of repetition or code duplication. It can be understood with the help of following lines of code −" }, { "code": null, "e": 62315, "s": 62174, "text": "element(by.model(‘event.name’)).sendKeys(‘An Event’);\nelement(by.model(‘event.name’)).sendKeys(‘Module 3’);\nelement(by.model(‘event.name’));" }, { "code": null, "e": 62555, "s": 62315, "text": "Due to the above challenges, it becomes headache for maintenance. It is because we have to find all the instances, replace with the new name, selector & other code. We also need to spend lots of time to keep tests in line with refactoring." }, { "code": null, "e": 62634, "s": 62555, "text": "Another challenge in UI testing is the happening of lots of failures in tests." }, { "code": null, "e": 62745, "s": 62634, "text": "We have seen some common challenges of UI testing. Some of the ways to handle such challenges are as follows −" }, { "code": null, "e": 63052, "s": 62745, "text": "The very first option for handling the above challenges is to update the references manually. The problem with this option is that we must do the manual change in the code as well as our tests. This can be done when you have one or two tests files but what if you have hundreds of tests files in a project?" }, { "code": null, "e": 63342, "s": 63052, "text": "Another option for handling above challenges is to use page objects. A page object is basically a plain JavaScript that encapsulates the properties of an Angular template. For example, the following specification file is written without and with page objects to understand the difference −" }, { "code": null, "e": 63363, "s": 63342, "text": "Without Page Objects" }, { "code": null, "e": 63682, "s": 63363, "text": "describe('angularjs homepage', function() {\n it('should greet the named user', function() {\n browser.get('http://www.angularjs.org');\n element(by.model('yourName')).sendKeys('Julie');\n var greeting = element(by.binding('yourName'));\n expect(greeting.getText()).toEqual('Hello Julie!');\n });\n});" }, { "code": null, "e": 63700, "s": 63682, "text": "With Page Objects" }, { "code": null, "e": 63864, "s": 63700, "text": "For writing the code with Page Objects, the first thing we need to do is to create a Page Object. Hence, a Page Object for the above example could look like this −" }, { "code": null, "e": 64280, "s": 63864, "text": "var AngularHomepage = function() {\n var nameInput = element(by.model('yourName'));\n var greeting = element(by.binding('yourName'));\n\n this.get = function() {\n browser.get('http://www.angularjs.org');\n };\n\n this.setName = function(name) {\n nameInput.sendKeys(name);\n };\n \n this.getGreetingText = function() {\n return greeting.getText();\n };\n};\nmodule.exports = new AngularHomepage();" }, { "code": null, "e": 64550, "s": 64280, "text": "We have seen the use of page objects in the above example to handle the challenges of UI testing. Next, we are going to discuss how we can use them to organize the tests. For this we need to modify the test script without modifying the functionality of the test script." }, { "code": null, "e": 64686, "s": 64550, "text": "To understand this concept we are taking the above configuration file with page objects. We need to modify the test script as follows −" }, { "code": null, "e": 64997, "s": 64686, "text": "var angularHomepage = require('./AngularHomepage');\ndescribe('angularjs homepage', function() {\n it('should greet the named user', function() {\n angularHomepage.get();\n\n angularHomepage.setName('Julie');\n \n expect(angularHomepage.getGreetingText()).toEqual\n ('Hello Julie!');\n });\n});" }, { "code": null, "e": 65081, "s": 64997, "text": "Here, note that the path to the page object will be relative to your specification." }, { "code": null, "e": 65215, "s": 65081, "text": "On the same note, we can also separate our test suite into various test suites. The configuration file then can be changed as follows" }, { "code": null, "e": 65866, "s": 65215, "text": "exports.config = {\n // The address of a running selenium server.\n seleniumAddress: 'http://localhost:4444/wd/hub',\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n // Spec patterns are relative to the location of the spec file. They may\n // include glob patterns.\n suites: {\n homepage: 'tests/e2e/homepage/**/*Spec.js',\n search: ['tests/e2e/contact_search/**/*Spec.js',\n 'tests/e2e/venue_search/**/*Spec.js']\n },\n\n // Options to be passed to Jasmine-node.\n jasmineNodeOpts: {\n showColors: true, // Use colors in the command line report.\n }\n};" }, { "code": null, "e": 66012, "s": 65866, "text": "Now, we can easily switch between running one or the other suite of tests. The following command will run only the homepage section of the test −" }, { "code": null, "e": 66060, "s": 66012, "text": "protractor protractor.conf.js --suite homepage\n" }, { "code": null, "e": 66137, "s": 66060, "text": "Similarly, we can run specific suites of tests with the command as follows −" }, { "code": null, "e": 66192, "s": 66137, "text": "protractor protractor.conf.js --suite homepage,search\n" }, { "code": null, "e": 66339, "s": 66192, "text": "Now that we have seen all the concepts of Protractor in the previous chapters, let us understand the debugging concepts in detail in this chapter." }, { "code": null, "e": 66905, "s": 66339, "text": "End-to-end (e2e) tests are very difficult to debug because they depend on the whole ecosystem of that application. We have seen that they depend upon various actions or particularly we can say that on prior actions like login and sometimes they depend on the permission. Another difficulty in debugging e2e tests is its dependency on WebDriver because it acts differently with different operating systems and browsers. Finally, debugging e2e tests also generates long error messages and makes it difficult to separate browser related issues and test process errors." }, { "code": null, "e": 67016, "s": 66905, "text": "There can be various reasons for the failure of test suites and followings are some well-known failure types −" }, { "code": null, "e": 67180, "s": 67016, "text": "When a command cannot be completed, an error is thrown by WebDriver. For example, a browser cannot get the defined address, or an element is not found as expected." }, { "code": null, "e": 67281, "s": 67180, "text": "An unexpected browser and OS-related failure happens when it fails to update the web driver manager." }, { "code": null, "e": 67391, "s": 67281, "text": "The failure of Protractor for Angular happens when Protractor didn’t find Angular in the library as expected." }, { "code": null, "e": 67656, "s": 67391, "text": "In this kind of failure, Protractor will fail when the useAllAngular2AppRoots parameter is not found in the configuration. It happens because, without this, the test process will look at one single root element while expecting more than one element in the process." }, { "code": null, "e": 67777, "s": 67656, "text": "This kind of failure happens when the test specification hit a loop or a long pool and fails to return the data in time." }, { "code": null, "e": 67871, "s": 67777, "text": "One of the most common test failures that shows what a normal expectation failure looks like." }, { "code": null, "e": 68179, "s": 67871, "text": "Suppose, if you have written test cases and they got failed then it is very important to know how to debug those test cases because it would be very hard to find the exact place where the error has occurred. While working with Protractor, you will get some long errors in red color font in the command line." }, { "code": null, "e": 68238, "s": 68179, "text": "The ways to debug in Protractor are explained here &miuns;" }, { "code": null, "e": 68413, "s": 68238, "text": "Using the pause method to debug the test cases in Protractor is one of the easiest ways. We can type the following command at the place we want to pause our test code &miuns;" }, { "code": null, "e": 68431, "s": 68413, "text": "browser.pause();\n" }, { "code": null, "e": 68603, "s": 68431, "text": "When the running codes hits the above command, it will pause the running program at that point. After that we can give the following commands according to our preference −" }, { "code": null, "e": 68777, "s": 68603, "text": "Whenever a command has exhausted, we must type C to move forward. If you will not type C, the test will not run the full code and it will fail due to Jasmine time out error." }, { "code": null, "e": 68931, "s": 68777, "text": "The benefit of interactive mode is that we can send the WebDriver commands to our browser. If we want to enter into the interactive mode, then type repl." }, { "code": null, "e": 69044, "s": 68931, "text": "For exiting the test from pause state and continuing the test from where it has stopped, we need to type Ctrl-C." }, { "code": null, "e": 69279, "s": 69044, "text": "In this example, we are having the below specification file named example_debug.js, protractor tries to identify an element with locator by.binding(‘mmmm’) but the URL(https://angularjs.org/ page has no element with specified locator." }, { "code": null, "e": 69647, "s": 69279, "text": "describe('Suite for protractor debugger',function(){\n it('Failing spec',function(){\n browser.get(\"http://angularjs.org\");\n element(by.model('yourName')).sendKeys('Vijay');\n //Element doesn't exist\n var welcomeText = \n element(by.binding('mmmm')).getText();\n expect('Hello '+welcomeText+'!').toEqual('Hello Ram!')\n });\n});" }, { "code": null, "e": 69811, "s": 69647, "text": "Now, for executing the above test we need to add browser.pause() code, where you want to pause the test, in the above specification file. It will look as follows −" }, { "code": null, "e": 70190, "s": 69811, "text": "describe('Suite for protractor debugger',function(){\n it('Failing spec',function(){\n browser.get(\"http://angularjs.org\");\n browser.pause();\n element(by.model('yourName')).sendKeys('Vijay');\n //Element doesn't exist\n var welcomeText = \n element(by.binding('mmmm')).getText();\n expect('Hello '+welcomeText+'!').toEqual('Hello Ram!')\n });\n});" }, { "code": null, "e": 70395, "s": 70190, "text": "But before executing, we need to do some changes in the configuration file also. We are doing the following changes in earlier used configuration file, named example_configuration.js in previous chapter −" }, { "code": null, "e": 71031, "s": 70395, "text": "// An example configuration file.\nexports.config = {\n directConnect: true,\n\n // Capabilities to be passed to the webdriver instance.\n capabilities: {\n 'browserName': 'chrome'\n },\n\n // Framework to use. Jasmine is recommended.\n framework: 'jasmine',\n\n // Spec patterns are relative to the current working directory when\n\n // protractor is called.\n specs: ['example_debug.js'],\n allScriptsTimeout: 999999,\n jasmineNodeOpts: {\n defaultTimeoutInterval: 999999\n },\n onPrepare: function () {\n browser.manage().window().maximize();\n browser.manage().timeouts().implicitlyWait(5000);\n }\n};" }, { "code": null, "e": 71064, "s": 71031, "text": "Now, run the following command −" }, { "code": null, "e": 71101, "s": 71064, "text": "protractor example_configuration.js\n" }, { "code": null, "e": 71150, "s": 71101, "text": "The debugger will start after the above command." }, { "code": null, "e": 71314, "s": 71150, "text": "Using the pause method to debug the test cases in Protractor is a bit advanced way. We can type the following command at the place we want to break our test code −" }, { "code": null, "e": 71335, "s": 71314, "text": "browser.debugger();\n" }, { "code": null, "e": 71530, "s": 71335, "text": "It uses the node debugger to debug the test code. For running the above command, we must type the following command in a separate command prompt which has opened from the test project location −" }, { "code": null, "e": 71567, "s": 71530, "text": "protractor debug protractor.conf.js\n" }, { "code": null, "e": 71734, "s": 71567, "text": "In this method, we also need to type C in the terminal for continuing the test code. But opposite to pause method, in this method it is to be typed for only one time." }, { "code": null, "e": 71983, "s": 71734, "text": "In this example, we are using the same specification file named bexample_debug.js, used above. The only difference is that instead of browser.pause(), we need to use browser.debugger() where we want to break the test code. It will look as follows −" }, { "code": null, "e": 72358, "s": 71983, "text": "describe('Suite for protractor debugger',function(){\n it('Failing spec',function(){\n browser.get(\"http://angularjs.org\");\n browser.debugger();\n element(by.model('yourName')).sendKeys('Vijay');\n //Element doesn't exist\n var welcomeText = element(by.binding('mmmm')).getText();\n expect('Hello '+welcomeText+'!').toEqual('Hello Ram!')\n });\n});" }, { "code": null, "e": 72449, "s": 72358, "text": "We are using the same configuration file, example_configuration.js, used in above example." }, { "code": null, "e": 72519, "s": 72449, "text": "Now, run the protractor test with following debug command line option" }, { "code": null, "e": 72562, "s": 72519, "text": "protractor debug example_configuration.js\n" }, { "code": null, "e": 72611, "s": 72562, "text": "The debugger will start after the above command." }, { "code": null, "e": 72685, "s": 72611, "text": "In this chapter, let us learn in detail about style guide for protractor." }, { "code": null, "e": 72938, "s": 72685, "text": "The style guide was created by two software engineers named, Carmen Popoviciu, front-end engineer at ING and Andres Dominguez, software engineer at Google. Hence, this style guide is also called Carmen Popoviciu and Google’s style guide for protractor." }, { "code": null, "e": 73006, "s": 72938, "text": "This style guide can be divided into the following five keypoints −" }, { "code": null, "e": 73020, "s": 73006, "text": "Generic rules" }, { "code": null, "e": 73038, "s": 73020, "text": "Project Structure" }, { "code": null, "e": 73057, "s": 73038, "text": "Locator strategies" }, { "code": null, "e": 73070, "s": 73057, "text": "Page Objects" }, { "code": null, "e": 73082, "s": 73070, "text": "Test suites" }, { "code": null, "e": 73180, "s": 73082, "text": "The following are some generic rules that must be taken care while using protractor for testing −" }, { "code": null, "e": 73541, "s": 73180, "text": "This is the very first generic rule given by Carmen and Andres. They suggested that we must not perform e2e test on the code that already been unit tested. The main reason behind it is that the unit tests are much faster than e2e tests. Another reason is that we must have to avoid duplicate tests (don’t perform both unit and e2e testing) for saving our time." }, { "code": null, "e": 73786, "s": 73541, "text": "Another important point recommended is that we must have to use only one configuration file. Do not create configuration file for each environment you are testing. You can use grunt-protractor-coverage in order to set up different environments." }, { "code": null, "e": 73952, "s": 73786, "text": "We must have to avoid using IF statements or FOR loops in our test cases because if we do so then the test may pass without testing anything or it may run very slow." }, { "code": null, "e": 74318, "s": 73952, "text": "Protractor can run the test parallelly when sharing is enabled. These files are then executed across different browsers as and when they become available. Carmen and Andres recommended to make the test independent at least at file level because the order in which they will be run by protractor is uncertain and moreover it is quite easy to run a test in isolation." }, { "code": null, "e": 74482, "s": 74318, "text": "Another important key point regarding the style guide of Protractor is the structure of your project. The following is the recommendation about project structure −" }, { "code": null, "e": 74875, "s": 74482, "text": "Carmen and Andres recommended that we must group our e2e tests in a structure that makes sense to the structure of your project. The reason behind this recommendation is that the finding of files would become easy and the folder structure would be more readable. This step will also separate e2e tests from unit tests. They recommended that the following kind of structure should be avoided −" }, { "code": null, "e": 75333, "s": 74875, "text": "|-- project-folder\n |-- app\n |-- css\n |-- img\n |-- partials\n home.html\n profile.html\n contacts.html\n |-- js\n |-- controllers\n |-- directives\n |-- services\n app.js\n ...\n index.html\n |-- test\n |-- unit\n |-- e2e\n home-page.js\n home-spec.js\n profile-page.js\n profile-spec.js\n contacts-page.js\n contacts-spec.js" }, { "code": null, "e": 75403, "s": 75333, "text": "On the other hand, they recommended the following kind of structure −" }, { "code": null, "e": 75896, "s": 75403, "text": "|-- project-folder\n |-- app\n |-- css\n |-- img\n |-- partials\n home.html\n profile.html\n contacts.html\n |-- js\n |-- controllers\n |-- directives\n |-- services\n app.js\n ...\n index.html\n |-- test\n |-- unit\n |-- e2e\n |-- page-objects\n home-page.js\n profile-page.js\n contacts-page.js\n home-spec.js\n profile-spec.js\n contacts-spec.js" }, { "code": null, "e": 75999, "s": 75896, "text": "The following are some locator strategies that must be taken care while using protractor for testing −" }, { "code": null, "e": 76274, "s": 75999, "text": "This is the first locator strategies that is recommended in protractor style guide. The reasons behind the same is that XPath is requires lots of maintenance because markup is very easily subject to change. Moreover, XPath expressions are the slowest and very hard to debug." }, { "code": null, "e": 76438, "s": 76274, "text": "Protractor-specific locators such as by.model and by.binding are short, specific and easy to read. With the help of them it is very easy to write our locator also." }, { "code": null, "e": 76443, "s": 76438, "text": "View" }, { "code": null, "e": 76659, "s": 76443, "text": "<ul class = \"red\">\n <li>{{color.name}}</li>\n <li>{{color.shade}}</li>\n <li>{{color.code}}</li>\n</ul>\n\n<div class = \"details\">\n <div class = \"personal\">\n <input ng-model = \"person.name\">\n </div>\n</div>" }, { "code": null, "e": 76722, "s": 76659, "text": "For the above code, it is recommended to avoid the following −" }, { "code": null, "e": 76841, "s": 76722, "text": "var nameElement = element.all(by.css('.red li')).get(0);\nvar personName = element(by.css('.details .personal input'));" }, { "code": null, "e": 76898, "s": 76841, "text": "On the other hand, the following is recommended to use −" }, { "code": null, "e": 77018, "s": 76898, "text": "var nameElement = element.all(by.css('.red li')).get(0);\nvar personName = element(by.css('.details .personal input'));\n" }, { "code": null, "e": 77123, "s": 77018, "text": "var nameElement = element(by.binding('color.name'));\nvar personName = element(by.model('person.name'));\n" }, { "code": null, "e": 77217, "s": 77123, "text": "When no Protractor locators are available, then it is recommended to prefer by.id and by.css." }, { "code": null, "e": 77390, "s": 77217, "text": "We must have to avoid text-based locators such as by.linkText, by.buttonText and by.cssContaningText because text for buttons, links and labels frequently change over time." }, { "code": null, "e": 77850, "s": 77390, "text": "As discussed earlier, page objects encapsulate information about the elements on our application page and due to this help us write cleaner test cases. A very useful advantage of page objects is that they can be reused across multiple tests and in case if the template of our application has been changed, we only need to update the page object. Followings are some recommendations for page objects that must be taken care while using protractor for testing −" }, { "code": null, "e": 78036, "s": 77850, "text": "It is recommended to use page objects to interact with the page under test because they can encapsulate information about the element on the page under test and they can be reused also." }, { "code": null, "e": 78154, "s": 78036, "text": "We should define each page object in its own file because it keeps the code clean and finding of things becomes easy." }, { "code": null, "e": 78332, "s": 78154, "text": "It is recommended that each page object should declare a single class so that we only need to export one class. For example, the following use of object file should be avoided −" }, { "code": null, "e": 78480, "s": 78332, "text": "var UserProfilePage = function() {};\nvar UserSettingsPage = function() {};\nmodule.exports = UserPropertiesPage;\nmodule.exports = UserSettingsPage;\n" }, { "code": null, "e": 78537, "s": 78480, "text": "But on the other hand, following is recommended to use −" }, { "code": null, "e": 78636, "s": 78537, "text": "/** @constructor */\nvar UserPropertiesPage = function() {};\n\nmodule.exports = UserPropertiesPage;\n" }, { "code": null, "e": 78770, "s": 78636, "text": "We should declare all the required modules at the top of the page object because it makes module dependencies clear and easy to find." }, { "code": null, "e": 79002, "s": 78770, "text": "It is recommended to instantiate all the page objects at the beginning of the test suite because this will separate dependencies from the test code as well as makes the dependencies available to all the specifications of the suite." }, { "code": null, "e": 79159, "s": 79002, "text": "We should not use expect() in page objects i.e. we should not make any assertions in our page objects because all the assertions must be done in test cases." }, { "code": null, "e": 79298, "s": 79159, "text": "Another reason is that the reader of the test should be able to understand the behavior of the application by reading the test cases only." }, { "code": null, "e": 79333, "s": 79298, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 79352, "s": 79333, "text": " SAYANTAN TARAFDAR" }, { "code": null, "e": 79385, "s": 79352, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 79401, "s": 79385, "text": " LuckyTrainings" }, { "code": null, "e": 79408, "s": 79401, "text": " Print" }, { "code": null, "e": 79419, "s": 79408, "text": " Add Notes" } ]
Constructors in Dart Programming
Constructors are methods that are used to initialize an object when it gets created. Constructors are mainly used to set the initial values for instance variables. The name of the constructor is the same as the name of the class. Constructors are similar to instance methods but they do not have a return type. All classes in Dart have their own default constructor, if you don't create any constructor for a class, the compiler will implicitly create a default constructor for every class by assigning the default values to the member variables. We can create a constructor in Dart something like this − class SomeClass { SomeClass(){ // constructor body } } There are two important rules that we should keep in mind when creating a constructor in Dart, these are − The name of the constructor should be the same name as the class name. The name of the constructor should be the same name as the class name. The constructor cannot have an explicit return type. The constructor cannot have an explicit return type. In total there are three types of constructors present in Dart, these mainly are − Default Constructor Default Constructor Parameterized Constructor Parameterized Constructor Named Constructor Named Constructor A constructor with no parameter is known as the default constructor. If you don't create a constructor explicitly, the compiler will create one implicitly. Live Demo class Student { Student(){ print("Inside Student Constructor"); } } void main(){ Student st = new Student(); } Inside Student Constructor We can also have constructors that take parameters, that can later be used to initialize instance variables. Live Demo class Student { Student(String name){ print("Student name : ${name}"); } } void main(){ Student st = new Student("Tuts!"); } Student name : Tuts! In Dart, named constructors are mainly used to define multiple constructors. Live Demo void main() { Student emp1 = new Student(); Student emp2 = new Student.namedConst('ST001'); } class Student{ Student() { print("Inside Student Constructor"); } Student.namedConst(String stCode) { print(stCode); } } Inside Student Constructor ST001
[ { "code": null, "e": 1292, "s": 1062, "text": "Constructors are methods that are used to initialize an object when it gets created. Constructors are mainly used to set the initial values for instance variables. The name of the constructor is the same as the name of the class." }, { "code": null, "e": 1373, "s": 1292, "text": "Constructors are similar to instance methods but they do not have a return type." }, { "code": null, "e": 1609, "s": 1373, "text": "All classes in Dart have their own default constructor, if you don't create any constructor for a class, the compiler will implicitly create a default constructor for every class by assigning the default values to the member variables." }, { "code": null, "e": 1667, "s": 1609, "text": "We can create a constructor in Dart something like this −" }, { "code": null, "e": 1734, "s": 1667, "text": "class SomeClass {\n SomeClass(){\n // constructor body\n }\n}" }, { "code": null, "e": 1841, "s": 1734, "text": "There are two important rules that we should keep in mind when creating a constructor in Dart, these are −" }, { "code": null, "e": 1912, "s": 1841, "text": "The name of the constructor should be the same name as the class name." }, { "code": null, "e": 1983, "s": 1912, "text": "The name of the constructor should be the same name as the class name." }, { "code": null, "e": 2036, "s": 1983, "text": "The constructor cannot have an explicit return type." }, { "code": null, "e": 2089, "s": 2036, "text": "The constructor cannot have an explicit return type." }, { "code": null, "e": 2172, "s": 2089, "text": "In total there are three types of constructors present in Dart, these mainly are −" }, { "code": null, "e": 2192, "s": 2172, "text": "Default Constructor" }, { "code": null, "e": 2212, "s": 2192, "text": "Default Constructor" }, { "code": null, "e": 2238, "s": 2212, "text": "Parameterized Constructor" }, { "code": null, "e": 2264, "s": 2238, "text": "Parameterized Constructor" }, { "code": null, "e": 2282, "s": 2264, "text": "Named Constructor" }, { "code": null, "e": 2300, "s": 2282, "text": "Named Constructor" }, { "code": null, "e": 2456, "s": 2300, "text": "A constructor with no parameter is known as the default constructor. If you don't create a constructor explicitly, the compiler will create one implicitly." }, { "code": null, "e": 2467, "s": 2456, "text": " Live Demo" }, { "code": null, "e": 2594, "s": 2467, "text": "class Student {\n Student(){\n print(\"Inside Student Constructor\");\n }\n}\n\nvoid main(){\n Student st = new Student();\n}" }, { "code": null, "e": 2621, "s": 2594, "text": "Inside Student Constructor" }, { "code": null, "e": 2730, "s": 2621, "text": "We can also have constructors that take parameters, that can later be used to initialize instance variables." }, { "code": null, "e": 2741, "s": 2730, "text": " Live Demo" }, { "code": null, "e": 2882, "s": 2741, "text": "class Student {\n Student(String name){\n print(\"Student name : ${name}\");\n }\n}\n\nvoid main(){\n Student st = new Student(\"Tuts!\");\n}" }, { "code": null, "e": 2903, "s": 2882, "text": "Student name : Tuts!" }, { "code": null, "e": 2980, "s": 2903, "text": "In Dart, named constructors are mainly used to define multiple constructors." }, { "code": null, "e": 2991, "s": 2980, "text": " Live Demo" }, { "code": null, "e": 3239, "s": 2991, "text": "void main() {\n\n Student emp1 = new Student();\n Student emp2 = new Student.namedConst('ST001');\n}\n\nclass Student{\n Student() {\n print(\"Inside Student Constructor\");\n }\n\n Student.namedConst(String stCode) {\n print(stCode);\n }\n}" }, { "code": null, "e": 3272, "s": 3239, "text": "Inside Student Constructor\nST001" } ]
How to create Dialog Box in ReactJS? - GeeksforGeeks
22 Jan, 2021 Dialogs inform users about a task and can contain critical information, require decisions, or involve multiple tasks. Material UI for React has this component available for us and it is very easy to integrate. We can create the dialog box in ReactJS using the following approach: Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import DialogActions from '@material-ui/core/DialogActions';import DialogContent from '@material-ui/core/DialogContent';import DialogTitle from '@material-ui/core/DialogTitle';import DialogContentText from '@material-ui/core/DialogContentText';import Dialog from '@material-ui/core/Dialog';import Button from '@material-ui/core/Button'; const App = () => { const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button variant="outlined" color="primary" onClick={handleClickOpen}> Open My Custom Dialog </Button> <Dialog open={open} onClose={handleClose}> <DialogTitle> Greetings from GeeksforGeeks </DialogTitle> <DialogContent> <DialogContentText> Do you do coding ? </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Close </Button> <Button onClick={handleClose} color="primary" autoFocus> Yes </Button> </DialogActions> </Dialog> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS
[ { "code": null, "e": 25893, "s": 25865, "text": "\n22 Jan, 2021" }, { "code": null, "e": 26173, "s": 25893, "text": "Dialogs inform users about a task and can contain critical information, require decisions, or involve multiple tasks. Material UI for React has this component available for us and it is very easy to integrate. We can create the dialog box in ReactJS using the following approach:" }, { "code": null, "e": 26223, "s": 26173, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26287, "s": 26223, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26319, "s": 26287, "text": "npx create-react-app foldername" }, { "code": null, "e": 26419, "s": 26319, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26433, "s": 26419, "text": "cd foldername" }, { "code": null, "e": 26542, "s": 26433, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 26572, "s": 26542, "text": "npm install @material-ui/core" }, { "code": null, "e": 26624, "s": 26572, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26642, "s": 26624, "text": "Project Structure" }, { "code": null, "e": 26771, "s": 26642, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26782, "s": 26771, "text": "Javascript" }, { "code": "import React from 'react';import DialogActions from '@material-ui/core/DialogActions';import DialogContent from '@material-ui/core/DialogContent';import DialogTitle from '@material-ui/core/DialogTitle';import DialogContentText from '@material-ui/core/DialogContentText';import Dialog from '@material-ui/core/Dialog';import Button from '@material-ui/core/Button'; const App = () => { const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <div> <Button variant=\"outlined\" color=\"primary\" onClick={handleClickOpen}> Open My Custom Dialog </Button> <Dialog open={open} onClose={handleClose}> <DialogTitle> Greetings from GeeksforGeeks </DialogTitle> <DialogContent> <DialogContentText> Do you do coding ? </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} color=\"primary\"> Close </Button> <Button onClick={handleClose} color=\"primary\" autoFocus> Yes </Button> </DialogActions> </Dialog> </div> );} export default App;", "e": 28033, "s": 26782, "text": null }, { "code": null, "e": 28146, "s": 28033, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28156, "s": 28146, "text": "npm start" }, { "code": null, "e": 28255, "s": 28156, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28266, "s": 28255, "text": "JavaScript" }, { "code": null, "e": 28274, "s": 28266, "text": "ReactJS" }, { "code": null, "e": 28291, "s": 28274, "text": "Web Technologies" }, { "code": null, "e": 28389, "s": 28291, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28429, "s": 28389, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28474, "s": 28429, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28535, "s": 28474, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28607, "s": 28535, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28653, "s": 28607, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28696, "s": 28653, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28741, "s": 28696, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28806, "s": 28741, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28874, "s": 28806, "text": "How to pass data from one component to other component in ReactJS ?" } ]
How to retrieve the MSI package product code using PowerShell?
You can retrieve the MSI installed packaged product code on the windows OS using PowerShell with Get-Package or Get-WmiObject command. In this example, we will retrieve the product code of 7-zip. Get-Package -Name '7-Zip 19.00 (x64 edition)' | fl * You can use the tagid or mentioned properties to filter the product code. To retrieve the package from the remote computer using the Get-Package method, use InvokeCommand. Invoke-Command -ComputerName TestMachine -ScriptBlock{ (Get-Package -Name '7-Zip 19.00 (x64 edition)').TagID } Another way to retrieve the product code is by using the WMI method as shown below. PS C:\> $product = Get-WmiObject win32_product | where{$_.name - eq "7-Zip 19.00 (x64 edition)"} PS C:\> $product.IdentifyingNumber To get the output from the remote computer, just specify the -ComputerName parameter. $product = Get-WmiObject win32_product -ComputerName TestMachine1, Testmachine2 | where{$_.name -eq "7-Zip 19.00 (x64 edition)"} $product.IdentifyingNumber
[ { "code": null, "e": 1197, "s": 1062, "text": "You can retrieve the MSI installed packaged product code on the windows OS using PowerShell with Get-Package or Get-WmiObject command." }, { "code": null, "e": 1258, "s": 1197, "text": "In this example, we will retrieve the product code of 7-zip." }, { "code": null, "e": 1311, "s": 1258, "text": "Get-Package -Name '7-Zip 19.00 (x64 edition)' | fl *" }, { "code": null, "e": 1385, "s": 1311, "text": "You can use the tagid or mentioned properties to filter the product code." }, { "code": null, "e": 1483, "s": 1385, "text": "To retrieve the package from the remote computer using the Get-Package method, use InvokeCommand." }, { "code": null, "e": 1597, "s": 1483, "text": "Invoke-Command -ComputerName TestMachine -ScriptBlock{\n (Get-Package -Name '7-Zip 19.00 (x64 edition)').TagID\n}" }, { "code": null, "e": 1681, "s": 1597, "text": "Another way to retrieve the product code is by using the WMI method as shown below." }, { "code": null, "e": 1813, "s": 1681, "text": "PS C:\\> $product = Get-WmiObject win32_product | where{$_.name -\neq \"7-Zip 19.00 (x64 edition)\"}\nPS C:\\> $product.IdentifyingNumber" }, { "code": null, "e": 1899, "s": 1813, "text": "To get the output from the remote computer, just specify the -ComputerName parameter." }, { "code": null, "e": 2055, "s": 1899, "text": "$product = Get-WmiObject win32_product -ComputerName\nTestMachine1, Testmachine2 | where{$_.name -eq \"7-Zip 19.00 (x64 edition)\"}\n$product.IdentifyingNumber" } ]
Java Program to Find the Area of Parallelogram - GeeksforGeeks
22 Dec, 2020 A parallelogram is a special type of quadrilateral that has equal and parallel opposite sides. The diagonals of a parallelogram bisect each other at 90 degrees. The area of a figure can be defined in geometry as the space occupied by a flat shape. A figure’s area is the number of unit squares that cover a closed figure’s surface. Using its base and height, the parallelogram area can be computed. Apart from it, the area of a parallelogram can also be evaluated, if the length of the parallel sides is known, along with any of the angles between the sides. Approach 1: Parallelogram Area Using Sides. Suppose a and b are the set of parallel sides of a parallelogram and h is the height, then based on the length of sides and height of it, the formula for its area is given by: Area = Base × Height Area = b × h Example: Input : base = 4, height = 6 Output: area = 24 Input : base = 10, height = 15 Output: area = 150 Approach: Take two input as base and height of Parallelogram.Apply the area of Parallelogram formula to calculate the area.Print the area. Take two input as base and height of Parallelogram. Apply the area of Parallelogram formula to calculate the area. Print the area. Below is the implementation of the above approach: Java // Java Program to Find the Area of Parallelogram import java.io.*; class GFG { public static void main(String[] args) { double base = 30.00; double height = 40.25; // formula for calculating the area double area_parallelogram = base * height; // displaying the area System.out.println("Area of the parallelogram = " + area_parallelogram); }} Area of the parallelogram = 1207.5 Approach 2: Parallelogram Area Without Height. If the height of the parallelogram is unknown to us, then we can use the trigonometry concept to find the area. Area = ab sin (x) Where a and b are the length of parallel sides and x is the angle between the sides of the parallelogram. Example: Input : length = 4, breadth = 6, angle(in degrees) = 30 Output: area = 11.999999999999998 Input : length = 5, breadth = 8, angle(in degrees) = 45 Output: area = 28.2842712474619 Approach: Take three input as length, breadth and angle between the sides of the Parallelogram.Apply the area of trapezium formula to calculate the area.Print the area. Take three input as length, breadth and angle between the sides of the Parallelogram. Apply the area of trapezium formula to calculate the area. Print the area. Below is the implementation of the above approach: Java // Java Program to Find the Area of Parallelogram import java.io.*; class GFG { public static void main(String[] args) { double length = 10.00; double breadth = 16.00; int angle = 60; double sin_x = Math.sin(Math.toRadians(angle)); // formula for calculating the area double area_parallelogram = length * breadth * sin_x; // displaying the area System.out.println("Area of the parallelogram = " + area_parallelogram); }} Area of the parallelogram = 138.56406460551017 Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors 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? Iterate through List in Java
[ { "code": null, "e": 25373, "s": 25345, "text": "\n22 Dec, 2020" }, { "code": null, "e": 25932, "s": 25373, "text": "A parallelogram is a special type of quadrilateral that has equal and parallel opposite sides. The diagonals of a parallelogram bisect each other at 90 degrees. The area of a figure can be defined in geometry as the space occupied by a flat shape. A figure’s area is the number of unit squares that cover a closed figure’s surface. Using its base and height, the parallelogram area can be computed. Apart from it, the area of a parallelogram can also be evaluated, if the length of the parallel sides is known, along with any of the angles between the sides." }, { "code": null, "e": 25976, "s": 25932, "text": "Approach 1: Parallelogram Area Using Sides." }, { "code": null, "e": 26152, "s": 25976, "text": "Suppose a and b are the set of parallel sides of a parallelogram and h is the height, then based on the length of sides and height of it, the formula for its area is given by:" }, { "code": null, "e": 26173, "s": 26152, "text": "Area = Base × Height" }, { "code": null, "e": 26186, "s": 26173, "text": "Area = b × h" }, { "code": null, "e": 26195, "s": 26186, "text": "Example:" }, { "code": null, "e": 26293, "s": 26195, "text": "Input : base = 4, height = 6\nOutput: area = 24\n\nInput : base = 10, height = 15\nOutput: area = 150" }, { "code": null, "e": 26303, "s": 26293, "text": "Approach:" }, { "code": null, "e": 26432, "s": 26303, "text": "Take two input as base and height of Parallelogram.Apply the area of Parallelogram formula to calculate the area.Print the area." }, { "code": null, "e": 26484, "s": 26432, "text": "Take two input as base and height of Parallelogram." }, { "code": null, "e": 26547, "s": 26484, "text": "Apply the area of Parallelogram formula to calculate the area." }, { "code": null, "e": 26563, "s": 26547, "text": "Print the area." }, { "code": null, "e": 26614, "s": 26563, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26619, "s": 26614, "text": "Java" }, { "code": "// Java Program to Find the Area of Parallelogram import java.io.*; class GFG { public static void main(String[] args) { double base = 30.00; double height = 40.25; // formula for calculating the area double area_parallelogram = base * height; // displaying the area System.out.println(\"Area of the parallelogram = \" + area_parallelogram); }}", "e": 27045, "s": 26619, "text": null }, { "code": null, "e": 27080, "s": 27045, "text": "Area of the parallelogram = 1207.5" }, { "code": null, "e": 27127, "s": 27080, "text": "Approach 2: Parallelogram Area Without Height." }, { "code": null, "e": 27239, "s": 27127, "text": "If the height of the parallelogram is unknown to us, then we can use the trigonometry concept to find the area." }, { "code": null, "e": 27257, "s": 27239, "text": "Area = ab sin (x)" }, { "code": null, "e": 27363, "s": 27257, "text": "Where a and b are the length of parallel sides and x is the angle between the sides of the parallelogram." }, { "code": null, "e": 27372, "s": 27363, "text": "Example:" }, { "code": null, "e": 27551, "s": 27372, "text": "Input : length = 4, breadth = 6, angle(in degrees) = 30\nOutput: area = 11.999999999999998\n\nInput : length = 5, breadth = 8, angle(in degrees) = 45\nOutput: area = 28.2842712474619" }, { "code": null, "e": 27561, "s": 27551, "text": "Approach:" }, { "code": null, "e": 27720, "s": 27561, "text": "Take three input as length, breadth and angle between the sides of the Parallelogram.Apply the area of trapezium formula to calculate the area.Print the area." }, { "code": null, "e": 27806, "s": 27720, "text": "Take three input as length, breadth and angle between the sides of the Parallelogram." }, { "code": null, "e": 27865, "s": 27806, "text": "Apply the area of trapezium formula to calculate the area." }, { "code": null, "e": 27881, "s": 27865, "text": "Print the area." }, { "code": null, "e": 27932, "s": 27881, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27937, "s": 27932, "text": "Java" }, { "code": "// Java Program to Find the Area of Parallelogram import java.io.*; class GFG { public static void main(String[] args) { double length = 10.00; double breadth = 16.00; int angle = 60; double sin_x = Math.sin(Math.toRadians(angle)); // formula for calculating the area double area_parallelogram = length * breadth * sin_x; // displaying the area System.out.println(\"Area of the parallelogram = \" + area_parallelogram); }}", "e": 28470, "s": 27937, "text": null }, { "code": null, "e": 28517, "s": 28470, "text": "Area of the parallelogram = 138.56406460551017" }, { "code": null, "e": 28524, "s": 28517, "text": "Picked" }, { "code": null, "e": 28529, "s": 28524, "text": "Java" }, { "code": null, "e": 28543, "s": 28529, "text": "Java Programs" }, { "code": null, "e": 28548, "s": 28543, "text": "Java" }, { "code": null, "e": 28646, "s": 28548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28661, "s": 28646, "text": "Stream In Java" }, { "code": null, "e": 28680, "s": 28661, "text": "Exceptions in Java" }, { "code": null, "e": 28701, "s": 28680, "text": "Constructors in Java" }, { "code": null, "e": 28731, "s": 28701, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28777, "s": 28731, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28803, "s": 28777, "text": "Java Programming Examples" }, { "code": null, "e": 28837, "s": 28803, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28884, "s": 28837, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28916, "s": 28884, "text": "How to Iterate HashMap in Java?" } ]
How to create a directory using Node.js ? - GeeksforGeeks
07 Oct, 2021 In this article, we will create a directory using NodeJS. NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory. Node.js fs.mkdir() method: Let’s create a new directory using fs.mkdir() method. Initially, we have single file index.js, as we can see in the given image. index.js Example: Edit the index.js file. Javascript const fs = require("fs"); const path = "./new-Directory"; fs.access(path, (error) => { // To check if the given directory // already exists or not if (error) { // If current directory does not exist // then create it fs.mkdir(path, (error) => { if (error) { console.log(error); } else { console.log("New Directory created successfully !!"); } }); } else { console.log("Given Directory already exists !!"); }}); Output: You can check the terminal output. After executing the above code, node.js will create a new directory if it does not exist. A new Directory named — “new-Directory” is created. Creating Parent Directories: If we want to create multilevel directory, fs.mkdir() has optional recursive Boolean value we can pass as a parameter. Javascript const fs = require("fs"); // Multilevel directoryconst path = "./directory1/directory2/new-directory"; fs.access(path, (error) => { // To check if given directory // already exists or not if (error) { // If current directory does not exist then create it fs.mkdir(path, { recursive: true }, (error) => { if (error) { console.log(error); } else { console.log("New Directory created successfully !!"); } }); } else { console.log("Given Directory already exists !!"); }}); Output: New Directory created successfully.index.js index.js We can see that a multilevel directory “directory1\directory2\new-directory” is created.index.js We can see that a multilevel directory “directory1\directory2\new-directory” is created. index.js Removing a folder: If we want to delete a given directory, we can use Node.js fs.rmdir() Method or Node.js fs.rmdirSync() Method, it will become complicated if the directory contain some file content. So we can use a third party package fs-extra provided by npm to delete the given directory. Let’s install the given package using npm. Run the following command in your command line npm install fs-extra Example: Now run the following code to delete the given directory Javascript const fs1 = require("fs-extra"); const path = "./directory1"; fs1.remove(path, (error) => { if (error) { console.log(error); } else { console.log("Folder Deleted Successfully !!"); }}); Output index.js Node.js fs.mkdirSync() method: Let’s create a new directory using fs.mkdirSync() method. Initially, we have single file index.js, as we can see in the given image. Example: Javascript const fs1 = require("fs-extra"); // Node.js program to demonstrate the// fs.mkdirSync() method const fs = require("fs"); const path = require("path"); // Using fs.exists() method to// Check that the directory exists or notconsole.log("Checking for directory" + path.join(__dirname, "Tisu"));fs.exists(path.join(__dirname, "Tisu"), (exists) => { console.log(exists ? "The directory already exists" : "Not found!");}); // Using fs.mkdirSync() method// To create the directory recursivelyfs.mkdirSync(path.join(__dirname, "Tisu"), true); // Using fs.exists() method to// Check that the directory exists or notfs.exists(path.join(__dirname, "Tisu"), (exists) => { console.log(exists ? "The directory already exists" : "Not found!");}); Output: NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Difference between Fetch and Axios.js for making http requests How to read and write Excel file in Node.js ? Express.js res.render() Function Express.js res.redirect() Function
[ { "code": null, "e": 39052, "s": 39024, "text": "\n07 Oct, 2021" }, { "code": null, "e": 39110, "s": 39052, "text": "In this article, we will create a directory using NodeJS." }, { "code": null, "e": 39311, "s": 39110, "text": "NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory." }, { "code": null, "e": 39467, "s": 39311, "text": "Node.js fs.mkdir() method: Let’s create a new directory using fs.mkdir() method. Initially, we have single file index.js, as we can see in the given image." }, { "code": null, "e": 39476, "s": 39467, "text": "index.js" }, { "code": null, "e": 39509, "s": 39476, "text": "Example: Edit the index.js file." }, { "code": null, "e": 39520, "s": 39509, "text": "Javascript" }, { "code": "const fs = require(\"fs\"); const path = \"./new-Directory\"; fs.access(path, (error) => { // To check if the given directory // already exists or not if (error) { // If current directory does not exist // then create it fs.mkdir(path, (error) => { if (error) { console.log(error); } else { console.log(\"New Directory created successfully !!\"); } }); } else { console.log(\"Given Directory already exists !!\"); }});", "e": 39986, "s": 39520, "text": null }, { "code": null, "e": 39994, "s": 39986, "text": "Output:" }, { "code": null, "e": 40029, "s": 39994, "text": "You can check the terminal output." }, { "code": null, "e": 40171, "s": 40029, "text": "After executing the above code, node.js will create a new directory if it does not exist. A new Directory named — “new-Directory” is created." }, { "code": null, "e": 40320, "s": 40171, "text": "Creating Parent Directories: If we want to create multilevel directory, fs.mkdir() has optional recursive Boolean value we can pass as a parameter. " }, { "code": null, "e": 40331, "s": 40320, "text": "Javascript" }, { "code": "const fs = require(\"fs\"); // Multilevel directoryconst path = \"./directory1/directory2/new-directory\"; fs.access(path, (error) => { // To check if given directory // already exists or not if (error) { // If current directory does not exist then create it fs.mkdir(path, { recursive: true }, (error) => { if (error) { console.log(error); } else { console.log(\"New Directory created successfully !!\"); } }); } else { console.log(\"Given Directory already exists !!\"); }});", "e": 40852, "s": 40331, "text": null }, { "code": null, "e": 40860, "s": 40852, "text": "Output:" }, { "code": null, "e": 40904, "s": 40860, "text": "New Directory created successfully.index.js" }, { "code": null, "e": 40913, "s": 40904, "text": "index.js" }, { "code": null, "e": 41010, "s": 40913, "text": "We can see that a multilevel directory “directory1\\directory2\\new-directory” is created.index.js" }, { "code": null, "e": 41099, "s": 41010, "text": "We can see that a multilevel directory “directory1\\directory2\\new-directory” is created." }, { "code": null, "e": 41108, "s": 41099, "text": "index.js" }, { "code": null, "e": 41309, "s": 41108, "text": "Removing a folder: If we want to delete a given directory, we can use Node.js fs.rmdir() Method or Node.js fs.rmdirSync() Method, it will become complicated if the directory contain some file content." }, { "code": null, "e": 41444, "s": 41309, "text": "So we can use a third party package fs-extra provided by npm to delete the given directory. Let’s install the given package using npm." }, { "code": null, "e": 41491, "s": 41444, "text": "Run the following command in your command line" }, { "code": null, "e": 41512, "s": 41491, "text": "npm install fs-extra" }, { "code": null, "e": 41578, "s": 41512, "text": "Example: Now run the following code to delete the given directory" }, { "code": null, "e": 41589, "s": 41578, "text": "Javascript" }, { "code": "const fs1 = require(\"fs-extra\"); const path = \"./directory1\"; fs1.remove(path, (error) => { if (error) { console.log(error); } else { console.log(\"Folder Deleted Successfully !!\"); }});", "e": 41786, "s": 41589, "text": null }, { "code": null, "e": 41793, "s": 41786, "text": "Output" }, { "code": null, "e": 41802, "s": 41793, "text": "index.js" }, { "code": null, "e": 41966, "s": 41802, "text": "Node.js fs.mkdirSync() method: Let’s create a new directory using fs.mkdirSync() method. Initially, we have single file index.js, as we can see in the given image." }, { "code": null, "e": 41975, "s": 41966, "text": "Example:" }, { "code": null, "e": 41986, "s": 41975, "text": "Javascript" }, { "code": "const fs1 = require(\"fs-extra\"); // Node.js program to demonstrate the// fs.mkdirSync() method const fs = require(\"fs\"); const path = require(\"path\"); // Using fs.exists() method to// Check that the directory exists or notconsole.log(\"Checking for directory\" + path.join(__dirname, \"Tisu\"));fs.exists(path.join(__dirname, \"Tisu\"), (exists) => { console.log(exists ? \"The directory already exists\" : \"Not found!\");}); // Using fs.mkdirSync() method// To create the directory recursivelyfs.mkdirSync(path.join(__dirname, \"Tisu\"), true); // Using fs.exists() method to// Check that the directory exists or notfs.exists(path.join(__dirname, \"Tisu\"), (exists) => { console.log(exists ? \"The directory already exists\" : \"Not found!\");});", "e": 42726, "s": 41986, "text": null }, { "code": null, "e": 42734, "s": 42726, "text": "Output:" }, { "code": null, "e": 42751, "s": 42734, "text": "NodeJS-Questions" }, { "code": null, "e": 42758, "s": 42751, "text": "Picked" }, { "code": null, "e": 42782, "s": 42758, "text": "Technical Scripter 2020" }, { "code": null, "e": 42790, "s": 42782, "text": "Node.js" }, { "code": null, "e": 42809, "s": 42790, "text": "Technical Scripter" }, { "code": null, "e": 42907, "s": 42809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42940, "s": 42907, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 42988, "s": 42940, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 43018, "s": 42988, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 43038, "s": 43018, "text": "How to update NPM ?" }, { "code": null, "e": 43092, "s": 43038, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 43129, "s": 43092, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 43192, "s": 43129, "text": "Difference between Fetch and Axios.js for making http requests" }, { "code": null, "e": 43238, "s": 43192, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 43271, "s": 43238, "text": "Express.js res.render() Function" } ]
Import Files and Images in ReactJS
In this article, we are going to see how to import CSS Files, images and functions defined in other folder to the main App.js file. In React, we need to dynamically import the images from their folder. In this example, we will define a project structure with the images and components already defined in the assets and components folder and then we are going to dynamically import them in our main App.js file. Project Structure App.js import React from 'react'; import MyComponent from './components/my -component.js'; import TutorialsPoint from './assets/img.png'; const App = () => { return ( <div> <img src={TutorialsPoint} /> <MyComponent /> </div> ); }; export default App; my-component.js import React from 'react'; const MyComponent = () => { return <div>Hii! This is the custom MyComponent</div>; }; export default MyComponent; This will produce the following result.
[ { "code": null, "e": 1194, "s": 1062, "text": "In this article, we are going to see how to import CSS Files, images and functions defined in other folder to the main App.js file." }, { "code": null, "e": 1264, "s": 1194, "text": "In React, we need to dynamically import the images from their folder." }, { "code": null, "e": 1473, "s": 1264, "text": "In this example, we will define a project structure with the images and components already defined in the assets and components folder and then we are going to dynamically import them in our main App.js file." }, { "code": null, "e": 1491, "s": 1473, "text": "Project Structure" }, { "code": null, "e": 1498, "s": 1491, "text": "App.js" }, { "code": null, "e": 1773, "s": 1498, "text": "import React from 'react';\nimport MyComponent from './components/my -component.js';\nimport TutorialsPoint from './assets/img.png';\n\nconst App = () => {\n return (\n <div>\n <img src={TutorialsPoint} />\n <MyComponent />\n </div>\n );\n};\nexport default App;" }, { "code": null, "e": 1789, "s": 1773, "text": "my-component.js" }, { "code": null, "e": 1935, "s": 1789, "text": "import React from 'react';\n\nconst MyComponent = () => {\n return <div>Hii! This is the custom MyComponent</div>;\n};\n\nexport default MyComponent;" }, { "code": null, "e": 1975, "s": 1935, "text": "This will produce the following result." } ]
Predicting Hotel Bookings with User Search Parameters | by Susan Li | Towards Data Science
A hotel market data and benchmark company STR and Google have published a report shows that tracking hotel search results can be a reliable estimate of hotel bookings. So, our goal today is to try to build a machine learning model to predict the event outcome (booking or just a click) for a user event, based on their search and other attributes associated with that user event. The data is public available that can be downloaded from Kaggle. we are only using the training set. The table below provides the schema of the data set. import datetimeimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_scoredf = pd.read_csv('train.csv.gz', sep=',').dropna()df = df.sample(frac=0.01, random_state=99) To be able to process locally, we will use 1% of the data. After that, we still have a large number of 241,179 records. df.shape (241179, 24) count_classes = pd.value_counts(df['is_booking'], sort = True).sort_index()count_classes.plot(kind = 'bar')plt.title("Booking or Not booking")plt.xlabel("Class")plt.ylabel("Frequency") It is obvious that our data is very imbalanced. We will have to deal with it. The process includes create new columns such as year, month, plan time and hotel nights. And remove the columns we do not need anymore afterwards. df["date_time"] = pd.to_datetime(df["date_time"]) df["year"] = df["date_time"].dt.year df["month"] = df["date_time"].dt.monthdf['srch_ci']=pd.to_datetime(df['srch_ci'],infer_datetime_format = True,errors='coerce')df['srch_co']=pd.to_datetime(df['srch_co'],infer_datetime_format = True,errors='coerce')df['plan_time'] = ((df['srch_ci']-df['date_time'])/np.timedelta64(1,'D')).astype(float)df['hotel_nights']=((df['srch_co']-df['srch_ci'])/np.timedelta64(1,'D')).astype(float)cols_to_drop = ['date_time', 'srch_ci', 'srch_co', 'user_id']df.drop(cols_to_drop, axis=1, inplace=True) Plot a correlation matrix using a heatmap to explore the correlation between features. correlation = df.corr()plt.figure(figsize=(18, 18))sns.heatmap(correlation, vmax=1, square=True,annot=True,cmap='viridis')plt.title('Correlation between different fearures') We do not see any two variables are very closely correlated. I will use under-sampling method to create re-sampled dataframe. booking_indices = df[df.is_booking == 1].indexrandom_indices = np.random.choice(booking_indices, len(df.loc[df.is_booking == 1]), replace=False)booking_sample = df.loc[random_indices]not_booking = df[df.is_booking == 0].indexrandom_indices = np.random.choice(not_booking, sum(df['is_booking']), replace=False)not_booking_sample = df.loc[random_indices]df_new = pd.concat([not_booking_sample, booking_sample], axis=0)print("Percentage of not booking clicks: ", len(df_new[df_new.is_booking == 0])/len(df_new))print("Percentage of booking clicks: ", len(df_new[df_new.is_booking == 1])/len(df_new))print("Total number of records in resampled data: ", len(df_new)) Shuffle the resampled dataframe. df_new = df_new.sample(frac=1).reset_index(drop=True) Assign features and label for the new dataframe. X = df_new.loc[:, df_new.columns != 'is_booking']y = df_new.loc[:, df_new.columns == 'is_booking'] Principal component analysis, or PCA, is a statistical technique to convert high dimensional data to low dimensional data by selecting the most important features that capture maximum information about the dataset. We hope PCA will help us find out the components with maximum variance. Standardize the dataset. scaler = StandardScaler()X=scaler.fit_transform(X)X Apply PCA. And we have 23 features in our data. pca = PCA(n_components=23)pca.fit(X) Calculate Eigenvalues. var=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=3)*100)var In the above array we see that the first feature explains 9.6% of the variance within our data set while the first two explain 17.8% and so on. If we employ all features we capture 100% of the variance within the dataset, thus we gain some by implementing an additional feature. No any single feature outstanding. Sort and select. plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.style.context('seaborn-whitegrid')plt.plot(var) Based on the plot above it’s clear that we should keep all the 23 features. Random Forest Classifier X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)pca = PCA() X_train = pca.fit_transform(X_train) X_test = pca.transform(X_test)classifier = RandomForestClassifier(max_depth=2, random_state=0) classifier.fit(X_train, y_train)y_pred = classifier.predict(X_test)cm = confusion_matrix(y_test, y_pred) print(cm) print('Accuracy', accuracy_score(y_test, y_pred)) Logistic Regression from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import PipelineX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)pca = PCA(n_components=23)logReg = LogisticRegression()pipe = Pipeline([('pca', pca), ('logistic', logReg)])pipe.fit(X_train, y_train)y_pred = pipe.predict(X_test)cm = confusion_matrix(y_test, y_pred) print(cm) print('Accuracy', accuracy_score(y_test, y_pred)) We may be able to boost the results to 70% by Exhaustive Grid Search. But it takes forever to run locally. I will not try it here. As you can see, it is not an easy task to predict hotel bookings from our current available data. We need more features, such as Average Daily Rate, users previous booking history, whether there is a special promotion, hotel online reviews and so on. Getting started with data collection before Machine Learning! Source code can be found on Github. Enjoy the rest of the week!
[ { "code": null, "e": 552, "s": 172, "text": "A hotel market data and benchmark company STR and Google have published a report shows that tracking hotel search results can be a reliable estimate of hotel bookings. So, our goal today is to try to build a machine learning model to predict the event outcome (booking or just a click) for a user event, based on their search and other attributes associated with that user event." }, { "code": null, "e": 706, "s": 552, "text": "The data is public available that can be downloaded from Kaggle. we are only using the training set. The table below provides the schema of the data set." }, { "code": null, "e": 1246, "s": 706, "text": "import datetimeimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlinefrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_scoredf = pd.read_csv('train.csv.gz', sep=',').dropna()df = df.sample(frac=0.01, random_state=99)" }, { "code": null, "e": 1366, "s": 1246, "text": "To be able to process locally, we will use 1% of the data. After that, we still have a large number of 241,179 records." }, { "code": null, "e": 1375, "s": 1366, "text": "df.shape" }, { "code": null, "e": 1388, "s": 1375, "text": "(241179, 24)" }, { "code": null, "e": 1573, "s": 1388, "text": "count_classes = pd.value_counts(df['is_booking'], sort = True).sort_index()count_classes.plot(kind = 'bar')plt.title(\"Booking or Not booking\")plt.xlabel(\"Class\")plt.ylabel(\"Frequency\")" }, { "code": null, "e": 1651, "s": 1573, "text": "It is obvious that our data is very imbalanced. We will have to deal with it." }, { "code": null, "e": 1798, "s": 1651, "text": "The process includes create new columns such as year, month, plan time and hotel nights. And remove the columns we do not need anymore afterwards." }, { "code": null, "e": 2378, "s": 1798, "text": "df[\"date_time\"] = pd.to_datetime(df[\"date_time\"]) df[\"year\"] = df[\"date_time\"].dt.year df[\"month\"] = df[\"date_time\"].dt.monthdf['srch_ci']=pd.to_datetime(df['srch_ci'],infer_datetime_format = True,errors='coerce')df['srch_co']=pd.to_datetime(df['srch_co'],infer_datetime_format = True,errors='coerce')df['plan_time'] = ((df['srch_ci']-df['date_time'])/np.timedelta64(1,'D')).astype(float)df['hotel_nights']=((df['srch_co']-df['srch_ci'])/np.timedelta64(1,'D')).astype(float)cols_to_drop = ['date_time', 'srch_ci', 'srch_co', 'user_id']df.drop(cols_to_drop, axis=1, inplace=True)" }, { "code": null, "e": 2465, "s": 2378, "text": "Plot a correlation matrix using a heatmap to explore the correlation between features." }, { "code": null, "e": 2639, "s": 2465, "text": "correlation = df.corr()plt.figure(figsize=(18, 18))sns.heatmap(correlation, vmax=1, square=True,annot=True,cmap='viridis')plt.title('Correlation between different fearures')" }, { "code": null, "e": 2700, "s": 2639, "text": "We do not see any two variables are very closely correlated." }, { "code": null, "e": 2765, "s": 2700, "text": "I will use under-sampling method to create re-sampled dataframe." }, { "code": null, "e": 3427, "s": 2765, "text": "booking_indices = df[df.is_booking == 1].indexrandom_indices = np.random.choice(booking_indices, len(df.loc[df.is_booking == 1]), replace=False)booking_sample = df.loc[random_indices]not_booking = df[df.is_booking == 0].indexrandom_indices = np.random.choice(not_booking, sum(df['is_booking']), replace=False)not_booking_sample = df.loc[random_indices]df_new = pd.concat([not_booking_sample, booking_sample], axis=0)print(\"Percentage of not booking clicks: \", len(df_new[df_new.is_booking == 0])/len(df_new))print(\"Percentage of booking clicks: \", len(df_new[df_new.is_booking == 1])/len(df_new))print(\"Total number of records in resampled data: \", len(df_new))" }, { "code": null, "e": 3460, "s": 3427, "text": "Shuffle the resampled dataframe." }, { "code": null, "e": 3514, "s": 3460, "text": "df_new = df_new.sample(frac=1).reset_index(drop=True)" }, { "code": null, "e": 3563, "s": 3514, "text": "Assign features and label for the new dataframe." }, { "code": null, "e": 3662, "s": 3563, "text": "X = df_new.loc[:, df_new.columns != 'is_booking']y = df_new.loc[:, df_new.columns == 'is_booking']" }, { "code": null, "e": 3949, "s": 3662, "text": "Principal component analysis, or PCA, is a statistical technique to convert high dimensional data to low dimensional data by selecting the most important features that capture maximum information about the dataset. We hope PCA will help us find out the components with maximum variance." }, { "code": null, "e": 3974, "s": 3949, "text": "Standardize the dataset." }, { "code": null, "e": 4026, "s": 3974, "text": "scaler = StandardScaler()X=scaler.fit_transform(X)X" }, { "code": null, "e": 4074, "s": 4026, "text": "Apply PCA. And we have 23 features in our data." }, { "code": null, "e": 4111, "s": 4074, "text": "pca = PCA(n_components=23)pca.fit(X)" }, { "code": null, "e": 4134, "s": 4111, "text": "Calculate Eigenvalues." }, { "code": null, "e": 4208, "s": 4134, "text": "var=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=3)*100)var" }, { "code": null, "e": 4522, "s": 4208, "text": "In the above array we see that the first feature explains 9.6% of the variance within our data set while the first two explain 17.8% and so on. If we employ all features we capture 100% of the variance within the dataset, thus we gain some by implementing an additional feature. No any single feature outstanding." }, { "code": null, "e": 4539, "s": 4522, "text": "Sort and select." }, { "code": null, "e": 4677, "s": 4539, "text": "plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.style.context('seaborn-whitegrid')plt.plot(var)" }, { "code": null, "e": 4753, "s": 4677, "text": "Based on the plot above it’s clear that we should keep all the 23 features." }, { "code": null, "e": 4778, "s": 4753, "text": "Random Forest Classifier" }, { "code": null, "e": 5180, "s": 4778, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)pca = PCA() X_train = pca.fit_transform(X_train) X_test = pca.transform(X_test)classifier = RandomForestClassifier(max_depth=2, random_state=0) classifier.fit(X_train, y_train)y_pred = classifier.predict(X_test)cm = confusion_matrix(y_test, y_pred) print(cm) print('Accuracy', accuracy_score(y_test, y_pred))" }, { "code": null, "e": 5200, "s": 5180, "text": "Logistic Regression" }, { "code": null, "e": 5639, "s": 5200, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import PipelineX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)pca = PCA(n_components=23)logReg = LogisticRegression()pipe = Pipeline([('pca', pca), ('logistic', logReg)])pipe.fit(X_train, y_train)y_pred = pipe.predict(X_test)cm = confusion_matrix(y_test, y_pred) print(cm) print('Accuracy', accuracy_score(y_test, y_pred))" }, { "code": null, "e": 5770, "s": 5639, "text": "We may be able to boost the results to 70% by Exhaustive Grid Search. But it takes forever to run locally. I will not try it here." }, { "code": null, "e": 6021, "s": 5770, "text": "As you can see, it is not an easy task to predict hotel bookings from our current available data. We need more features, such as Average Daily Rate, users previous booking history, whether there is a special promotion, hotel online reviews and so on." }, { "code": null, "e": 6083, "s": 6021, "text": "Getting started with data collection before Machine Learning!" } ]
ASP.NET - Error Handling
Error handling in ASP.NET has three aspects: Tracing - tracing the program execution at page level or application level. Tracing - tracing the program execution at page level or application level. Error handling - handling standard errors or custom errors at page level or application level. Error handling - handling standard errors or custom errors at page level or application level. Debugging - stepping through the program, setting break points to analyze the code Debugging - stepping through the program, setting break points to analyze the code In this chapter, we will discuss tracing and error handling and in this chapter, we will discuss debugging. To understand the concepts, create the following sample application. It has a label control, a dropdown list, and a link. The dropdown list loads an array list of famous quotes and the selected quote is shown in the label below. It also has a hyperlink which has points to a nonexistent link. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Tracing, debugging and error handling </title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblheading" runat="server" Text="Tracing, Debuggin and Error Handling"> </asp:Label> <br /> <br /> <asp:DropDownList ID="ddlquotes" runat="server" AutoPostBack="True" onselectedindexchanged="ddlquotes_SelectedIndexChanged"> </asp:DropDownList> <br /> <br /> <asp:Label ID="lblquotes" runat="server"> </asp:Label> <br /> <br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="mylink.htm">Link to:</asp:HyperLink> </div> </form> </body> </html> The code behind file: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string[,] quotes = { {"Imagination is more important than Knowledge.", "Albert Einsten"}, {"Assume a virtue, if you have it not" "Shakespeare"}, {"A man cannot be comfortable without his own approval", "Mark Twain"}, {"Beware the young doctor and the old barber", "Benjamin Franklin"}, {"Whatever begun in anger ends in shame", "Benjamin Franklin"} }; for (int i=0; i<quotes.GetLength(0); i++) ddlquotes.Items.Add(new ListItem(quotes[i,0], quotes[i,1])); } } protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e) { if (ddlquotes.SelectedIndex != -1) { lblquotes.Text = String.Format("{0}, Quote: {1}", ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue); } } } To enable page level tracing, you need to modify the Page directive and add a Trace attribute as shown: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" Trace ="true" %> Now when you execute the file, you get the tracing information: It provides the following information at the top: Session ID Status Code Time of Request Type of Request Request and Response Encoding The status code sent from the server, each time the page is requested shows the name and time of error if any. The following table shows the common HTTP status codes: Under the top level information, there is Trace log, which provides details of page life cycle. It provides elapsed time in seconds since the page was initialized. The next section is control tree, which lists all controls on the page in a hierarchical manner: Last in the Session and Application state summaries, cookies, and headers collections followed by list of all server variables. The Trace object allows you to add custom information to the trace output. It has two methods to accomplish this: the Write method and the Warn method. Change the Page_Load event handler to check the Write method: protected void Page_Load(object sender, EventArgs e) { Trace.Write("Page Load"); if (!IsPostBack) { Trace.Write("Not Post Back, Page Load"); string[,] quotes = ....................... } } Run to observe the effects: To check the Warn method, let us forcibly enter some erroneous code in the selected index changed event handler: try { int a = 0; int b = 9 / a; }catch (Exception e) { Trace.Warn("UserAction", "processing 9/a", e); } Try-Catch is a C# programming construct. The try block holds any code that may or may not produce error and the catch block catches the error. When the program is run, it sends the warning in the trace log. Application level tracing applies to all the pages in the web site. It is implemented by putting the following code lines in the web.config file: <system.web> <trace enabled="true" /> </system.web> Although ASP.NET can detect all runtime errors, still some subtle errors may still be there. Observing the errors by tracing is meant for the developers, not for the users. Hence, to intercept such occurrence, you can add error handing settings in the web.config file of the application. It is application-wide error handling. For example, you can add the following lines in the web.config file: <configuration> <system.web> <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> </system.web> <configuration> The <customErrors> section has the possible attributes: Mode : It enables or disables custom error pages. It has the three possible values: On : displays the custom pages. Off : displays ASP.NET error pages (yellow pages) remoteOnly : It displays custom errors to client, display ASP.NET errors locally. Mode : It enables or disables custom error pages. It has the three possible values: On : displays the custom pages. Off : displays ASP.NET error pages (yellow pages) remoteOnly : It displays custom errors to client, display ASP.NET errors locally. defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors. defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors. To put different custom error pages for different type of errors, the <error> sub tags are used, where different error pages are specified, based on the status code of the errors. To implement page level error handling, the Page directive could be modified: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %> Because ASP.NET Debugging is an important subject in itself, so we would discuss it in the next chapter separately. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2392, "s": 2347, "text": "Error handling in ASP.NET has three aspects:" }, { "code": null, "e": 2468, "s": 2392, "text": "Tracing - tracing the program execution at page level or application level." }, { "code": null, "e": 2544, "s": 2468, "text": "Tracing - tracing the program execution at page level or application level." }, { "code": null, "e": 2639, "s": 2544, "text": "Error handling - handling standard errors or custom errors at page level or application level." }, { "code": null, "e": 2734, "s": 2639, "text": "Error handling - handling standard errors or custom errors at page level or application level." }, { "code": null, "e": 2817, "s": 2734, "text": "Debugging - stepping through the program, setting break points to analyze the code" }, { "code": null, "e": 2900, "s": 2817, "text": "Debugging - stepping through the program, setting break points to analyze the code" }, { "code": null, "e": 3008, "s": 2900, "text": "In this chapter, we will discuss tracing and error handling and in this chapter, we will discuss debugging." }, { "code": null, "e": 3301, "s": 3008, "text": "To understand the concepts, create the following sample application. It has a label control, a dropdown list, and a link. The dropdown list loads an array list of famous quotes and the selected quote is shown in the label below. It also has a hyperlink which has points to a nonexistent link." }, { "code": null, "e": 4471, "s": 3301, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"errorhandling._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>\n Tracing, debugging and error handling\n </title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n \n <div>\n <asp:Label ID=\"lblheading\" runat=\"server\" Text=\"Tracing, Debuggin and Error Handling\">\n </asp:Label>\n \n <br /> <br />\n \n <asp:DropDownList ID=\"ddlquotes\" runat=\"server\" AutoPostBack=\"True\" onselectedindexchanged=\"ddlquotes_SelectedIndexChanged\">\n </asp:DropDownList>\n \n <br /> <br />\n \n <asp:Label ID=\"lblquotes\" runat=\"server\">\n </asp:Label>\n \n <br /> <br />\n \n <asp:HyperLink ID=\"HyperLink1\" runat=\"server\" NavigateUrl=\"mylink.htm\">Link to:</asp:HyperLink>\n </div>\n \n </form>\n </body>\n \n</html>" }, { "code": null, "e": 4493, "s": 4471, "text": "The code behind file:" }, { "code": null, "e": 5489, "s": 4493, "text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n string[,] quotes = \n {\n {\"Imagination is more important than Knowledge.\", \"Albert Einsten\"},\n {\"Assume a virtue, if you have it not\" \"Shakespeare\"},\n {\"A man cannot be comfortable without his own approval\", \"Mark Twain\"},\n {\"Beware the young doctor and the old barber\", \"Benjamin Franklin\"},\n {\"Whatever begun in anger ends in shame\", \"Benjamin Franklin\"}\n };\n \n for (int i=0; i<quotes.GetLength(0); i++)\n ddlquotes.Items.Add(new ListItem(quotes[i,0], quotes[i,1]));\n }\n }\n \n protected void ddlquotes_SelectedIndexChanged(object sender, EventArgs e)\n {\n if (ddlquotes.SelectedIndex != -1)\n {\n lblquotes.Text = String.Format(\"{0}, Quote: {1}\", ddlquotes.SelectedItem.Text, ddlquotes.SelectedValue);\n }\n }\n}" }, { "code": null, "e": 5593, "s": 5489, "text": "To enable page level tracing, you need to modify the Page directive and add a Trace attribute as shown:" }, { "code": null, "e": 5722, "s": 5593, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\"\n Inherits=\"errorhandling._Default\" Trace =\"true\" %>" }, { "code": null, "e": 5786, "s": 5722, "text": "Now when you execute the file, you get the tracing information:" }, { "code": null, "e": 5836, "s": 5786, "text": "It provides the following information at the top:" }, { "code": null, "e": 5847, "s": 5836, "text": "Session ID" }, { "code": null, "e": 5859, "s": 5847, "text": "Status Code" }, { "code": null, "e": 5875, "s": 5859, "text": "Time of Request" }, { "code": null, "e": 5891, "s": 5875, "text": "Type of Request" }, { "code": null, "e": 5921, "s": 5891, "text": "Request and Response Encoding" }, { "code": null, "e": 6088, "s": 5921, "text": "The status code sent from the server, each time the page is requested shows the name and time of error if any. The following table shows the common HTTP status codes:" }, { "code": null, "e": 6252, "s": 6088, "text": "Under the top level information, there is Trace log, which provides details of page life cycle. It provides elapsed time in seconds since the page was initialized." }, { "code": null, "e": 6349, "s": 6252, "text": "The next section is control tree, which lists all controls on the page in a hierarchical manner:" }, { "code": null, "e": 6477, "s": 6349, "text": "Last in the Session and Application state summaries, cookies, and headers collections followed by list of all server variables." }, { "code": null, "e": 6629, "s": 6477, "text": "The Trace object allows you to add custom information to the trace output. It has two methods to accomplish this: the Write method and the Warn method." }, { "code": null, "e": 6691, "s": 6629, "text": "Change the Page_Load event handler to check the Write method:" }, { "code": null, "e": 6914, "s": 6691, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n Trace.Write(\"Page Load\");\n \n if (!IsPostBack)\n {\n Trace.Write(\"Not Post Back, Page Load\");\n string[,] quotes = \n .......................\n }\n}" }, { "code": null, "e": 6942, "s": 6914, "text": "Run to observe the effects:" }, { "code": null, "e": 7055, "s": 6942, "text": "To check the Warn method, let us forcibly enter some erroneous code in the selected index changed event handler:" }, { "code": null, "e": 7168, "s": 7055, "text": "try\n{\n int a = 0;\n int b = 9 / a;\n}catch (Exception e)\n{\n Trace.Warn(\"UserAction\", \"processing 9/a\", e);\n}" }, { "code": null, "e": 7375, "s": 7168, "text": "Try-Catch is a C# programming construct. The try block holds any code that may or may not produce error and the catch block catches the error. When the program is run, it sends the warning in the trace log." }, { "code": null, "e": 7521, "s": 7375, "text": "Application level tracing applies to all the pages in the web site. It is implemented by putting the following code lines in the web.config file:" }, { "code": null, "e": 7576, "s": 7521, "text": "<system.web>\n <trace enabled=\"true\" />\n</system.web>" }, { "code": null, "e": 7749, "s": 7576, "text": "Although ASP.NET can detect all runtime errors, still some subtle errors may still be there. Observing the errors by tracing is meant for the developers, not for the users." }, { "code": null, "e": 7972, "s": 7749, "text": "Hence, to intercept such occurrence, you can add error handing settings in the web.config file of the application. It is application-wide error handling. For example, you can add the following lines in the web.config file:" }, { "code": null, "e": 8272, "s": 7972, "text": "<configuration>\n <system.web>\n \n <customErrors mode=\"RemoteOnly\" defaultRedirect=\"GenericErrorPage.htm\">\n <error statusCode=\"403\" redirect=\"NoAccess.htm\"\t/>\n <error statusCode=\"404\" redirect=\"FileNotFound.htm\" />\n </customErrors>\n \n </system.web>\n<configuration>" }, { "code": null, "e": 8328, "s": 8272, "text": "The <customErrors> section has the possible attributes:" }, { "code": null, "e": 8579, "s": 8328, "text": "Mode : It enables or disables custom error pages. It has the three possible values:\n\nOn : displays the custom pages.\nOff : displays ASP.NET error pages (yellow pages)\nremoteOnly : It displays custom errors to client, display ASP.NET errors locally.\n\n" }, { "code": null, "e": 8663, "s": 8579, "text": "Mode : It enables or disables custom error pages. It has the three possible values:" }, { "code": null, "e": 8695, "s": 8663, "text": "On : displays the custom pages." }, { "code": null, "e": 8745, "s": 8695, "text": "Off : displays ASP.NET error pages (yellow pages)" }, { "code": null, "e": 8827, "s": 8745, "text": "remoteOnly : It displays custom errors to client, display ASP.NET errors locally." }, { "code": null, "e": 8922, "s": 8827, "text": "defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors." }, { "code": null, "e": 9017, "s": 8922, "text": "defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors." }, { "code": null, "e": 9197, "s": 9017, "text": "To put different custom error pages for different type of errors, the <error> sub tags are used, where different error pages are specified, based on the status code of the errors." }, { "code": null, "e": 9275, "s": 9197, "text": "To implement page level error handling, the Page directive could be modified:" }, { "code": null, "e": 9430, "s": 9275, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\"\n Inherits=\"errorhandling._Default\" Trace =\"true\" ErrorPage=\"PageError.htm\" %>" }, { "code": null, "e": 9546, "s": 9430, "text": "Because ASP.NET Debugging is an important subject in itself, so we would discuss it in the next chapter separately." }, { "code": null, "e": 9581, "s": 9546, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9595, "s": 9581, "text": " Anadi Sharma" }, { "code": null, "e": 9630, "s": 9595, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9653, "s": 9630, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 9687, "s": 9653, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 9707, "s": 9687, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9742, "s": 9707, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9759, "s": 9742, "text": " University Code" }, { "code": null, "e": 9794, "s": 9759, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9811, "s": 9794, "text": " University Code" }, { "code": null, "e": 9845, "s": 9811, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 9860, "s": 9845, "text": " Bhrugen Patel" }, { "code": null, "e": 9867, "s": 9860, "text": " Print" }, { "code": null, "e": 9878, "s": 9867, "text": " Add Notes" } ]
R Factors
Factors are used to categorize data. Examples of factors are: Demography: Male/Female Music: Rock, Pop, Classic, Jazz Training: Strength, Stamina To create a factor, use the factor() function and add a vector as argument: Result: [1] Jazz Rock Classic Classic Pop Jazz Rock Jazz Levels: Classic Jazz Pop Rock You can see from the example above that that the factor has four levels (categories): Classic, Jazz, Pop and Rock. To only print the levels, use the levels() function: Result: [1] "Classic" "Jazz" "Pop" "Rock" You can also set the levels, by adding the levels argument inside the factor() function: Result: [1] "Classic" "Jazz" "Pop" "Rock" "Other" Use the length() function to find out how many items there are in the factor: Result: [1] 8 To access the items in a factor, refer to the index number, using [] brackets: Access the third item: Result: [1] Classic Levels: Classic Jazz Pop Rock To change the value of a specific item, refer to the index number: Change the value of the third item: Result: [1] Pop Levels: Classic Jazz Pop Rock Note that you cannot change the value of a specific item if it is not already specified in the factor. The following example will produce an error: Trying to change the value of the third item ("Classic") to an item that does not exist/not predefined ("Opera"): Result: Warning message: In `[<-.factor`(`*tmp*`, 3, value = "Opera") : invalid factor level, NA generated However, if you have already specified it inside the levels argument, it will work: Change the value of the third item: Result: [1] Opera Levels: Classic Jazz Pop Rock Opera We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 62, "s": 0, "text": "Factors are used to categorize data. Examples of factors are:" }, { "code": null, "e": 86, "s": 62, "text": "Demography: Male/Female" }, { "code": null, "e": 118, "s": 86, "text": "Music: Rock, Pop, Classic, Jazz" }, { "code": null, "e": 146, "s": 118, "text": "Training: Strength, Stamina" }, { "code": null, "e": 223, "s": 146, "text": "To create a factor, use the factor() function \nand add a vector as argument:" }, { "code": null, "e": 231, "s": 223, "text": "Result:" }, { "code": null, "e": 327, "s": 231, "text": "[1] Jazz Rock Classic Classic Pop Jazz Rock Jazz\nLevels: Classic Jazz Pop Rock\n" }, { "code": null, "e": 442, "s": 327, "text": "You can see from the example above that that the factor has four levels (categories): Classic, Jazz, Pop and Rock." }, { "code": null, "e": 495, "s": 442, "text": "To only print the levels, use the levels() function:" }, { "code": null, "e": 503, "s": 495, "text": "Result:" }, { "code": null, "e": 548, "s": 503, "text": "[1] \"Classic\" \"Jazz\" \"Pop\" \"Rock\" \n" }, { "code": null, "e": 638, "s": 548, "text": "You can also set the levels, by adding the levels argument inside the \nfactor() function:" }, { "code": null, "e": 646, "s": 638, "text": "Result:" }, { "code": null, "e": 699, "s": 646, "text": "[1] \"Classic\" \"Jazz\" \"Pop\" \"Rock\" \"Other\"\n" }, { "code": null, "e": 777, "s": 699, "text": "Use the length() function to find out how many items there are in the factor:" }, { "code": null, "e": 785, "s": 777, "text": "Result:" }, { "code": null, "e": 792, "s": 785, "text": "[1] 8\n" }, { "code": null, "e": 871, "s": 792, "text": "To access the items in a factor, refer to the index number, using [] brackets:" }, { "code": null, "e": 894, "s": 871, "text": "Access the third item:" }, { "code": null, "e": 902, "s": 894, "text": "Result:" }, { "code": null, "e": 945, "s": 902, "text": "[1] Classic\nLevels: Classic Jazz Pop Rock\n" }, { "code": null, "e": 1012, "s": 945, "text": "To change the value of a specific item, refer to the index number:" }, { "code": null, "e": 1048, "s": 1012, "text": "Change the value of the third item:" }, { "code": null, "e": 1056, "s": 1048, "text": "Result:" }, { "code": null, "e": 1095, "s": 1056, "text": "[1] Pop\nLevels: Classic Jazz Pop Rock\n" }, { "code": null, "e": 1244, "s": 1095, "text": "Note that you cannot change the value of a specific item if it is not already \nspecified in the factor. The following example will produce an error:" }, { "code": null, "e": 1359, "s": 1244, "text": "Trying to change the value of the third item (\"Classic\") to an item that does \nnot exist/not predefined (\"Opera\"):" }, { "code": null, "e": 1367, "s": 1359, "text": "Result:" }, { "code": null, "e": 1469, "s": 1367, "text": "Warning message:\nIn `[<-.factor`(`*tmp*`, 3, value = \"Opera\") :\n invalid factor level, NA generated\n" }, { "code": null, "e": 1553, "s": 1469, "text": "However, if you have already specified it inside the levels argument, it will work:" }, { "code": null, "e": 1589, "s": 1553, "text": "Change the value of the third item:" }, { "code": null, "e": 1597, "s": 1589, "text": "Result:" }, { "code": null, "e": 1644, "s": 1597, "text": "[1] Opera\nLevels: Classic Jazz Pop Rock Opera\n" }, { "code": null, "e": 1677, "s": 1644, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1719, "s": 1677, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1826, "s": 1719, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1845, "s": 1826, "text": "[email protected]" } ]
How to plot the outline of the outer edges on a Matplotlib line in Python?
To plot the outline of the outer edges on a Matplotlib in Python, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Plot x and y data points with linewidth set to 10 and 5, to get the visible outline edges. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-10, 10, 100) y = np.sin(x) plt.plot(x, y, lw=10, color='red') plt.plot(x, y, lw=5, color='yellow') plt.show()
[ { "code": null, "e": 1162, "s": 1062, "text": "To plot the outline of the outer edges on a Matplotlib in Python, we can take the following steps −" }, { "code": null, "e": 1238, "s": 1162, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1278, "s": 1238, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1369, "s": 1278, "text": "Plot x and y data points with linewidth set to 10 and 5, to get the visible outline edges." }, { "code": null, "e": 1411, "s": 1369, "text": "To display the figure, use show() method." }, { "code": null, "e": 1685, "s": 1411, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(-10, 10, 100)\ny = np.sin(x)\n\nplt.plot(x, y, lw=10, color='red')\nplt.plot(x, y, lw=5, color='yellow')\n\nplt.show()" } ]
Neural Language Models | by Arun Jagota | Towards Data Science
In NLP, a language model is a probability distribution over sequences on an alphabet of tokens. A central problem in language modeling is to learn a language model from examples, such as a model of English sentences from a training set of sentences. Language models have many uses. Such as... Suggest auto-completes: the user types a few characters (or words) on a web search engine or a smartphone and likely extensions are suggested. Recognize handwriting: An image-based recognition system augmented with a language model has improved accuracy. For instance, it can guess a word from its context even when it is not legible. Recognize speech: As in handwriting recognition, augmenting a speech system with a language model improves its accuracy. Detect and correct spelling errors Translate languages: To translate text from one language to another, it helps to have language models for the languages. In [1], we discussed statistical language models, a standard paradigm in the 1990s and earlier. In the past few decades, a new paradigm has emerged: neural language models. This is the subject of this post. Why neural language models over statistical ones? The short answer: they yield state-of-the-art accuracy with minimal human engineering. Why? The short answer is: due to a combination of two breakthroughs in recent decades — deep neural networks, and recurrent ones. (Exponential increases in computing power and availability of training data also helped tremendously.) Distributed representations, i.e. word embeddings, also played a role. In this post, we will cover recurrent neural networks (including deep ones) in the context of language modeling. We start with the master equations. These are the most important take-away equations in this post. Beyond defining the language modeling problem precisely, they also serve to frame various approaches to its solution. Let P(w1, w2, ..., wn) denote the probability of a sequence (w1, w2, ..., wn) of tokens. The aim of learning is to learn such probabilities from a training set of sequences. Consider the related problem of predicting the next token of a sequence. We model this as P(wn | w1, w2, ..., wn-1). Note that if we can accurately predict the probabilities P(wn | w1, w2, ..., wn-1), we can chain them together to get P(w1, w2, ..., wn) = P(w1)*P(w2 | w1)*P(w3 | w1, w2)* ... *P(wn | w1, w2, ..., wn-1) Most learning approaches target language modeling as the next token prediction problem. This is a problem of supervised learning. The input is (w1, w2, ..., wn-1). The output we seek is a probability distribution over the various values that wn could take. Note that the output is a fixed-length probability vector. (The dimensionality could be very high, though. Hundreds of thousands to millions for a language model on English sentences.) The input is not a fixed-length vector. Its length, n, varies. In many use cases, n can often be large, in the 100s or even 1000s. This is the primary factor that makes this problem difficult. Statistical approaches to estimating P(wn | w1, w2, ..., wn-1) when n is large must make some assumptions. Without them the problem is intractable. Consider n = 101 and say the alphabet just has two symbols: 0 and 1. The minimal training set size to reliably estimate P(wn | w1, w2, ..., wn-1) is of the order 2100. This is because the input can be any one of those choices, and we want to be able to predict the next token reasonably in each case. The most widely-made assumption in statistical approaches is Markovian. Specifically, P(wn | w1, w2, ..., wn-1) is approximated by P(wn | wn-k, ..., wn-1). This assumes that the next token probabilities depend only on the last k tokens. Here k is fixed, often to a small number (2 or 3). See [1] for more on this topic. This vastly simplifies the problem. At the cost of not being able to model long-range influences. Here is an example, from [2], of a long-range influence. “Jane walked into the room. John walked in too. It was late in the day, and everyone was walking home after a long day at work. Jane said hi to ___” The answer is John. This requires remembering the one occurrence of John about 25 words back. Another nice example is from [4]. I grew up in France ... I speak fluent French. Predicting French involves remembering France which may have occurred many sentences back. Neural language models address this “long-range influence” problem. Additionally, they also address the short-range influence problem better, specifically with automatically learnable feature vectors. (Statistical approaches can also use features; however, these are human-engineered.) Early Neural Language Model One of the early neural language models, as described in [3], is feedforward in nature. Whereas the more recent approaches are now all recurrent, we start with this model because it has some insightful characteristics that will set the stage for the ones that follow. As with many statistical language models, this model is kth-order Markovian. That is, for n greater than k, it assumes that P(wn | w1, w2, ..., wn-1) equals P(wn | wn-k, ..., wn-1). It uses distributed representations for input words. Distributed representations, more recently also called word embeddings, go back to the 1980s. A distributed representation of a word maps it onto a d-dimensional numeric space. Distributed representations are learned by algorithms in ways that encourage semantically-related words to be near each other in this space. The intuition for using learned distributed representations is the hope that they pick up useful features of words involving semantic relateness. For example, if one sees Paris and France in the same text, this might help the model to make sensible inferences involving the context French, such as in our language example: I speak fluent ___. This model then concatenates the distributed representations of wn-k, ..., wn-1. This forms the input vector, of dimensionality k*d. Since we want the output to be a probability distribution over the entire lexicon of words, this network uses N output neurons, where N is the size of the lexicon. A hidden layer sits between the input and output layers. As in any other multilayer neural network, the hidden layer maps the input to a vector of features. (The neurons are sigmoid-like, specifically tanh.) This mapping is done via learnable weights from each input neuron to each hidden neuron. The mapping from the hidden layer to the output layer uses the softmax function. This is because we want the output to be a probability distribution over the output neurons. The softmax function is parametrized by weights, one per (hidden neuron, output neuron) pair. The parameters of this network are learned in the usual way, i.e. via backpropagation using stochastic gradient descent. The distributed representations of the various words can also be learned during this process. Alternatively, such distributed representations can be pre-learned in some other way (e.g. word2vec) and just used here. It is worth noting that when the size of the lexicon N is huge (say in the millions) the computations involving the output layer become the bottlenecks. This is because the predicted output on a particular input needs to be a probability distribution over the entire lexicon. A more serious limitation is that this network, just like typical statistical models, cannot model influences among words that are more than k units apart. In our John-Jane example, we would need k to be at least 25 for us to have any hope of making the right inference. Statistical models that explicitly compute P(wn | wn-k, ..., wn-1) require memory that grows exponentially with k. This neural network model scales better. It uses k*d*h + h*N parameters, where h is the number of hidden neurons. So the number of parameters increases only linearly with k. Recurrent Neural Networks Recurrent neural networks are appealing for language modeling because they are not constrained by k. That is, in principle, they can learn arbitrarily long-range influences. That said, it does require some special engineering for them to do so. We’ll start by describing a basic RNN. We will see that it has difficulty learning long-range influences. We will then discuss modifications to this RNN to alleviate this issue. Basic RNN As a black box, i.e. from the input-output interface, an RNN looks like a feedforward neural network at first glance. It inputs a vector x and outputs a vector y. There is a twist though. The RNN expects to receive, as input, a sequence of vectors x(1), ..., x(T), one vector at a time, and outputs a sequence of vectors y(1), ..., y(T). The output y(t) at time t is influenced not only by x(t), rather by the entire sequence x(1), ..., x(t) of inputs received till then. This is what makes the RNN powerful. And the associated learning problem challenging. The RNN must carry state. Somehow it must summarize the history x(1), ..., x(t-1) into a state, which we will call h(t-1), from which it can predict y(t) well. When the input x(t) is presented, it first updates its state to h(t). In effect, x(t) becomes part of the history of the inputs it has seen. It then produces the output vector y(t) from h(t). We can write this formally as h(t) = f(h(t-1),x(t))y(t) = g(h(t)) In summary, the RNN may be viewed as having two parts: A part that updates the state based on the current state and the new input.A part that transforms the current state to an output. A part that updates the state based on the current state and the new input. A part that transforms the current state to an output. Part 1 is reminiscent of finite-state automata in computer science. Part 1+Part 2 is a finite-state transducer in computer science terms. The state in an FSA may be viewed as a categorical variable. By contrast, the state in an RNN is a multi-dimensional vector. The latter facilitates compact distributed representations of states that can generalize well, a major advantage of modern neural representations. The icing on the cake (to put it mildly) is that both the state-change and the state-to-output behaviors of the RNN can be learned automatically from a training set of (input sequence, output sequence) pairs. The State-change and Output Functions Following the usual neural network ‘design pattern’ inspired in part by biological neural networks and approved by statistics, we’ll use f(h,x) = S1(Whh*h + Wxh*x)g(h) = S2(Why*h) Here S1 and S2 are often sigmoid-shaped functions, typically the tanh or the logistic function. f(h,x) computes the next state as a linear combination of the current state and the next input pushed through the squashing function S1. g(h) computes the output as a linear transformation of the new state pushed through the squashing function S2. RNNs in Language Modeling A fundamental use case of RNNs is in language modeling. Recall that in language modeling, our primary interest is in estimating P(wn | w1, w2, ..., wn-1). A natural way to model this in an RNN is to model wn-1 as the input vector x(n-1), the history w1, w2, ..., wn-2 as the state vector h(n-1) and the output y(n-1) as a probability vector over the lexicon of words. For these purposes, it is natural to use the softmax function as the output function S2. Rather than a squashing function. S2(u) exponentiates each component of u and then normalizes the resulting vector to form a probability distribution. That is, it divides each exponentiated value by the sum of the exponentiated values. Structurally, this is analogous to the feedforward neural language model described earlier. The output dimensionality is N, the size of the lexicon. The input dimensionality is based on how words are represented. If words are represented locally, i.e. as a one-hot encoding, the input dimensionality is N. If words are represented in a distributed fashion, the input dimensionality is the dimensionality of this distributed representation. The state vector’s dimensionality is analogous to a hidden layer’s dimensionality, and controls the capacity of the corresponding feature space. A sequence of words w1, w2, ..., wn-1, wn may be turned into a training instance for this RNN-based language model. The sequence of inputs is x(1), ..., x(n-1), the sequence of vectors of the first n-1 words. The target output y(n-1) associated with this sequence is derived from the word wn. It’s the probability vector with all its mass concentrated on the dimension that corresponds to this word. Let’s pause to reflect on this. The output dimensionality is always N, as we are trying to learn a language model. This does have learning consequences as N is often very large. The input dimensionality may be distributed and compact or local and typically huge, i.e. N. There are trade-offs. A local representation imparts the model with a high capacity and is capable of making fine-grained distinctions. Each word has its own vector of weights to each hidden neuron. Models using distributed representations of words in the input layer are exponentially-more compact, may learn much faster, and potentially generalize better. They can leverage distributed representations that have already been learned by effective algorithms such as word2vec and enhancements, possibly from a huge corpus of documents. Learning The learnable parameters are the matrices of weights Whh, Wxh, and Why inside the state transition and the output functions. Whh controls the influence of the current state vector on the next state vector, Wxh the influence of the next input vector on the next state vector, and Why the influence of the next state vector on the next output vector. To understand how learning happens, it helps to unfold the recurrent neural network in time, as depicted below. Now consider the input x(t) at time t along with its target output y(t). Keeping in mind that the mapping we seek to learn is really to output close to y(t) on the sequence of inputs x(1), x(2), ..., x(t) we can depict the situation as a multilayer feedforward neural network unfolded in time as depicted below. So we can use backpropagation to learn the weights inside the functions f and g. With a twist. All the f’s in the picture above must have the same weights. They are all the same f! Okay, we can make this happen by summing up the changes to each weight in f across all the layers. One way to think of this is as follows. Let’s imagine we have two versions of the network: the constrained version (whose weights are shared as explained in the previous paragraph) and the unconstrained version which is a multi-layer neural network with no weight sharing, i.e., each instance of f has its own weights. Before the learning on the pair (x(t), y(t)), we’ll initialize each weight in the unconstrained version to the corresponding weight from the constrained version. We then run one iteration of online backpropagation (aka stochastic gradient descent) to update the weights on the unconstrained version. From these, we derive the new weights on the constrained version by taking, for each constrained weight, the average of the unconstrained weights that map to it. Well, all this sounds great in principle. However, note that the unfolded network can be very deep! So if there is a long-range influence, meaning that x(t-k) strongly influences y(t) for a large k (say k = 100), the back-propagated error signal may get very weak. This is because every instance in which the error is back-propagated through f attenuates the error since f is a squashing function. Let’s expand on the last sentence in the previous paragraph, in the setting below. To simplify the explanation, we use a feedforward neural network with two hidden layers. Plus the input and the output layer. All layers have a single neuron each. All layers except the input one have a sigmoidal transfer function. hi denotes the output of the neuron at layer i, and ni denotes the input to this neuron. So we have hi = s(ni) where s denotes the sigmoid function. We also have ni = w(i-1)*h(i-1). Note that to simplify the notation h0 denotes the input and h3 the output. In this illustration, we will use the loss function L = 1⁄2 (y-h3)2. The backpropagation algorithm computes the gradient of L with respect to each weight wi (applying the chain rule when needed) to decide on the change to make to the weight. More precisely, Delta wi = -n*dL/dwi Here n is the learning rate. The ‘-’ is there because we are doing gradient descent (since we want to minimize the error). So now it comes down to computing dL/dwi for the various weights wi. Let’s start with w2. By the chain rule, dL/dw2 = (dL/dh3)*(dh3/dn3)*(dn3/dw2) = 2(y-h3)*s(n3)*(1-s(n3))*h2 Admittedly we are overloading notation a bit. In the above, h2, h3 and n3 denote both the variables (neurons) and their particular values on the input x = h0. We are also using the fact that the derivative of the sigmoid function ds/dn equals s(n)*(1-s(n)). Also that, for i > 0, dni/dw(i-1) equals h(i-1). Similarly, with a slightly deeper application of the chain rule, we get dL/dw1 = (dL/dh3)*(dh3/dn3)*(dn3/dh2)*(dh2/dn2)*(dn2/dw1) = 2(y-h3)*s(n3)*(1-s(n3))*w2*s(n2)*(1-s(n2)*h1 Now imagine adding more hidden layers to our network (keeping the topology and the transfer functions the same) and computing dL/dw0. dL/dw0 = 2(y-h(K))*s(nK)*(1-s(nK))*w(K-1)*s(n(K-1))*(1-s(n(K-1))*...*w1*s(n1)*(1-s(n1))*h0 Consider any one term s(ni)*(1-s(ni)). This product is always less than 1⁄4. Combining all such pairs in dL/dw0 produces a multiplicative factor whose value is less than (1⁄4)^K. In view of this, as K increases, dL/dw0 approaches 0 very very quickly. This is the vanishing gradient problem. This has a potentially disastrous consequence in our example. We may never learn w0. A Long-range Example Next, let’s see a realistic example with long-range influences. We will use it to illustrate that learning such influences is the issue with basic RNNs, not the ability to represent them. This same example will also help illustrate the mechanisms of a more advanced RNN that alleviate this issue. We’d like to process a long sequence of English words and output a 1 if the word terrorist appears at least once, and 0 if not. Were terrorist to occur only once and very early on in the sequence, this event needs to be remembered until the very end. Why not just output a 1 immediately after terrorist is detected, else keep going? That would be tweaking the mechanisms of a general solution to this particular problem. This tweak would not generalize to the broader class of problems exhibiting long-range influences, of which this is just one illustrative example. The XOR example was used in the feedforward neural networks setting in exactly the same way. Viewed as a problem to solve, XOR is trivial. Just input two binary numbers and output the binary number that is their exclusive OR. However, viewed as an example to illustrate issues with certain feedforward architectures and to test improvements, it has turned out to be quite useful. The XOR is linearly inseparable. This is why classifiers capable of only linear discrimination fail. Indeed in the 1980s, the XOR was often used as a benchmark to test and demonstrate the learning ability of backpropagation in the setting of multi-layer perceptrons — feedforward neural networks with a hidden layer and sigmoidal neurons. Okay, back to our example. Let’s refine the problem description for our purposes here. The input x(1), ..., x(t) is a sequence of vectors where x(i) represents the ith word. The output y(t) is 1 if the word terrorist appears in this sequence and 0 if not. So the output is a binary sequence aligned with the input sequence and has a very simple structure: 0*1*. We will represent a word as a one-hot encoded vector. The vector’s dimensionality is the size of the lexicon. The bit corresponding to the word being represented is 1, the rest are 0. Now consider a basic RNN for this problem. Its input and output structure has already been specified. What about the state? Let’s set the state vector’s dimensionality to be the same as that of the input vector. We’d like hi(t) to be close to 1 if the word indexed by i was seen at least once among x(1), ..., x(t), and close to 0 if not. This is certainly feasible representationally, with the choice hi(t) = sigmoid(a*hi(t-1) + b*xi(t) + c) It is easy to choose a, b, and c, for example, a = b = 1 and c slightly negative, so that hi(t) is essentially an OR of hi(t-1) and xi(t). This is what we want. Once we have processed the entire sequence, we can simply set y(t) to hi(t), where i indexes the particular word we care about (in our case, terrorist). We can write this in the form y = g(W*h(t)) where g is a sigmoid. W is the vector whose ith position is sufficiently positive (e.g. 1) and the rest are 0. Now let’s look at this situation from the perspective of learning. Imagine that we have a training set of (document, label) pairs where label is 1 if a certain word appears somewhere in the document and 0 if not. We can assume that the labeling is consistent, i.e. this “certain word” is always the same. However, we are not told what that word is. So there are two issues here: (i) the learner must deduce which of the potentially millions of words best discriminates the two classes and (ii) learn only sequentially as described earlier in the basic RNN section. Focusing on (ii), backpropagation-through-time may need to propagate error gradients far back in time in many cases. Such gradients can vanish as discussed in an earlier section. The consequence of this is that if in most positive instances, the last occurrence of the “certain word” (in our example, terrorist) appears well before the last word in the document, the learner will not be able to establish the connection between this occurrence and the output is 1. If our positive instances are at least somewhat long documents, in most of them, the last occurrence of the word terrorist will indeed be well before the document’s end. Before closing this section, we’d like to add that now that we have opened the door to the labeling driving the learning, this problem becomes broader in its import. We can pose any binary classification problem on text this way, so long as we have a rich enough data set. It’s up to the recurrent neural network solution to figure out which words and which sequential structure helps to solve the problem. That said if one’s aim is to solve such a problem and if there isn’t a compelling case to be made for sequential learning, one should try non-recurrent binary classifier algorithms first. Such as feedforward neural networks, random forests, naive Bayes classifiers, ... Gated Recurrent Unit (GRU) We now turn our attention to more advanced recurrent neural networks, capable of capturing long-range influences. Two such networks in wide use are the LSTM and the GRU. We will describe the GRU as its mechanisms are simpler while remaining effective for capturing long-range influences. At a high level, the GRU works in the same fashion as a basic RNN. The input is a sequence of vectors presented one by one. The GRU maintains state, capturing some key aspect of what it has seen so far. This state combined with the next input determines the next state. The advancement comes in the state transition function. We’ll use the example we just introduced to build up the description of the GRU. Consider the state update function of the basic RNN for this example h(t) = sigmoid(A*h(t-1) + B*x(t) + C) The GRU will build up h(t) from h(t-1) and x(t) in a different way. It introduces the notion of a new memory hnew(t) derived from h(t-1) and x(t). The process of deriving this new memory from h(t-1) and x(t) has a mechanism that first runs each component of h(t-1) through a filtering gate. Think of this as letting the network selectively pay differing attention to different components of h(t-1) for this purpose. This filter, let’s call it si(t), takes on a value between 0 and 1. Filtering involves multiplying hi(t-1) by si(t). In vector notation we write this as s(t) o h(t-1). The filtered version of h(t-1) is then linearly combined with x(t) and passed through a component-wise tanh. The full equation is hnew(t) = tanh(A*x(t) + B*(s(t) o h(t-1)) + C) The new memory is then combined with the old memory to form the updated memory, in a manner that will be described soon. By contrast, in the basic RNN, the updated memory is formed only from the old memory. What would be a good hnew(t) in our example? Let’s capture the desired behavior in pseudocode. IF i indexes terrorist and xi(t) is 1 hnew,i(t) = ~ 1IF i indexes terrorist and hi(t-1) is ~ 1 hnew,i(t) = ~ 1IF i indexes some other word hnew,i(t) = ~ 0ALL ELSE hnew,i(t) = ~ 0 hnew,i(t) is close to 0 for any word i other than terrorist. hnew,terrorist(t) is close to 1 if the new input x(t) is terrorist or if terrorist has been seen previously, in which case hi(t-1) would be close to 1. Can we choose the learning parameters to emulate this desired behavior? First, we will set C to the vector of 0s. The THEN clause of the first IF can be executed via an appropriate choice of matrix A. Specifically, set Aii equal to 1 and all the rest of A’s elements to 0. The THEN clause of the second IF can be executed by choosing si(t) to be near 1 for i indexing terrorist and near 0 for the rest. Choose B as a matrix of positive values, e.g. all 1s. Under these conditions on A, B, and s(t), hnew,i(t) will be set near 0 when neither of the first two THEN clauses triggers. At this stage the reader might wonder, what have we really gained? If the last occurrence of the word terrorist appeared way before the current t, will not computing hnew,i(t) from the long chain of triggerings of the second THEN clause — the one whose antecedent is “i indexes terrorist and hi(t-1) is near 1” — have the same diluting effect. The reader is right to wonder this way. We have not yet completed the GRU’s description. Once we have all the mechanisms in place we will get a better sense of how they all come together to alleviate the vanishing gradient problem. The GRU uses a second gate, called the update gate, to control the relative contributions of the old and the new memories towards the updated memory. By contrast, the basic RNN derives the updated memory just from the old memory. Before diving into the update gate, let’s complete the description of the filtering gate. Filtering Gate Equation This is s(t) = sigmoid(D*x(t) + E*h(t-1) + F) Here D, E, and F are the matrices and vectors of the learnable parameters that control the behavior of the gate. In our terrorist example, the behavior we sought from s(t) was to simply project out the value of hi(t-1), where i indexes the word terrorist. How well we can learn this behavior automatically from a training set is a whole different story. Example to illustrate the update gate mechanism To build intuition about the update gate and the role it plays, a different example will help. We’d like to do anomaly detection in a time series using an RNN. We want the anomaly detector to not only detect anomalies but also adapt to new normals. Let’s illustrate this with an example. 1, 2, 3, 2, 4, 2, 3, 2, 3, 23, 22, 25, 24, 22, 23, 24, 25, 21, ... We process this time series from left to right. The value 23 is way outside the range of the values we have seen to this point, so we deem it anomalous. As we should. As we continue to process values to the right of this anomaly, we see that a new normal is developing. (Specifically, a level shift.) At some point soon the anomaly detector should adapt to this, and start treating it as the ‘normal’. For example, stop deeming values between 20 and 25 as anomalies. We’d also like to be able to control ‘at some point soon’ more finely by providing a labeled data set. By this, we mean that a time series comes labeled with which points are anomalous and which not. The RNN should be able to deduce, for any particular time series, how aggressively or conservatively we want to transition to the ‘new normal’. This would be the time-series specific behavior inferred from the historical labeling. One way to approach this is to train the RNN to forecast the next value in the time series. If the actual next value differs a lot from the forecasted next value then deem that value as being anomalous. RNNs are in principle suited to one-step forecasting because this problem is similar to learning a language model. In both cases, we want to predict the next input from the historical inputs. The model that the RNN learns during its incremental learning on the target of forecasting the next value may be interpreted as the current model of ‘normal values’. Now suppose that this RNN is a basic RNN. What happens when it encounters the first occurrence of 23. We hope it flags it as anomalous. What happens next? It incrementally trains on 23, as it would on any new value. The effect of this is that, as we see more values at this level, the model will gradually adjust to this new level. That is, it is building a ‘new normal’. So far so good. It is going in the direction we want. If this 23 was an outlier, i.e. a spike, not a level shift, the RNN would soon adjust back to the old normal. So all seems good. Let’s look at this more closely though. As the basic RNN is incapable of remembering the old normal (the one based on the values in the time series to the left of the first occurrence of 23) it must unlearn its accommodation of 23 towards an evolving new normal. Which in hindsight it can see was an anomaly. The GRU addresses this situation better. Just like the basic RNN, the GRU learns to adapt its ‘normal’ by forecasting the next value and adjusting its model based on the forecast error. Unlike the basic RNN, the GRU works with two models: one a slower evolving model, captured in h(t), the second a faster-evolving model, captured in hnew(t). In effect, the GRU can remember both the ‘old normal’ and a tentative ‘new normal’ at the same time. Its composite model is a combination of these two. This gives it the flexibility that should the ‘new normal’ later turn out to be a ‘false alarm’, i.e. an anomaly, it can just use the ‘old normal’. By contrast, the basic RNN would have to unlearn it. It also lets the GRU adapt quicker to the new normal in case it is not a ‘false alarm’. This behavior is summarized in the pseudocode below. Evolve two models, a slow one and a fast one, based on forecasting and feedback from forecasting errors.IF the new fast model is somehow deemed as capturing a transient phenomenon continue treating the 'old model' as the normalELSE evolve towards the 'new fast model' as the normal Update Gate Usage Equation Let’s call this gate u. ui(t) is between 0 and 1. The equation for the updated memory using this gate is hi(t) = (1-ui(t))*hi(t-1) + ui(t)*hnew,i(t) which, in vector notation, is h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t) Anomaly Detection Example Refined Next, let’s refine the discussion on our anomaly detection example. We’ll use one-dimensional input and output vectors since we are working with a time series. For the state vector, we might consider a higher dimensionality. Whatever we feel is appropriate to capture the ‘normal’ characteristics of the recent values of the time series. For instance, if we wish to capture not only (a smoothed version) of the most recent value of the time series but also its trend, we might choose two dimensions. By choosing the dimensions of h and hnew with care, we can detect different types of anomalies. To detect point anomalies, two-dimensional state vectors may suffice. One dimension models the central tendency, e.g. mean or median, the second the dispersion, e.g. standard deviation or a more robust version. To, additionally, detect trend changes, we may want additional dimensions, ones that model characteristics of trends. Like h(t), hnew(t) is also a model of recent values. That said, as hinted by the name, hnew(t) is a model of even more recent values than h(t). For example, h(t) might be a slow-moving average and hnew(t) a fast-moving average. Now suppose the most recent values in the time series are anomalous. Let’s say we know this fact. That is, the anomalies are labeled. We can capture this in the value of the update gate u(t) where t is one of these anomalous time points. This gives us control over whether we want the most recent values (which we know are anomalous) to update our ‘normalcy’ model or not. For instance, we might not want to alter our ‘normalcy’ model if we are in the midst of an anomaly. We can make this happen by setting the components of u(t) close to 0. If we are in a ‘normal’ region we want our normalcy model to adapt quicker to the data. Update Gate Equation We have seen how the update gate’s value is used in constructing the updated memory from the new memory and the old memory. But how is the update gate’s value itself calculated? This is done as below. u(t) = sigmoid(A*x(t) + B*h(t-1) + C) Here A, B, and C are the matrices and vectors of the learnable parameters. Putting All the Equations Together We have covered all the mechanisms inside the GRU. Let’s put all the equations together and review the end-to-end flow. At a single time t that is. s(t) = sigmoid(A*x(t) + B*h(t-1) + C)hnew(t) = tanh(D*x(t) + E*(s(t) o h(t-1)) + F)u(t) = sigmoid(G*x(t) + H*h(t-1) + I)h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t) Let’s now walk through the end-to-end flow at a single time t. We assume that the learning has already happened. The new input x(t) arrives at time t. The RNN’s current memory state is h(t-1). First, from these two we compute the value s(t) of the filtering gate. Now we have what we need to compute the value hnew(t) of the new memory. So we do that. Next, we compute the update gate’s value u(t) from x(t) and h(t-1). Note that the equations for computing s(t) and u(t) have the same form. The differing behaviors arise from the different learned parameters. Finally, we compute the updated memory h(t) from the old memory h(t-1) and the new memory hnew(t) using the update gate u(t) to combine the two. “Learning” The parameters to be learned are the matrices A, B, D, E, G, and H and the vectors C, F, and I. We have placed this section’s name in quotes intentionally. Rather than describe learning in the usual purely supervised way, we will just convey intuition on how the various mechanisms in the GRU might be learned from some combination of human-driven biasing and self-supervised or supervised machine learning. We will illustrate these in the anomaly detection example. In this illustration, we will be taking some liberties with the GRU. That is, we will tweak its mechanisms as appropriate. Our aim is to provide insights into the mechanisms and variations by way of an example. Two for one: Anomaly detection also solves forecasting We think it's helpful to add that buried within the anomaly detection approach we describe below are certain time series forecasting tasks. We want to call this out here because, in the process of describing how to use the (somewhat tweaked) GRU to solve time series anomaly detection problems, we will also be implicitly covering how to solve time series forecasting problems. So you get insights into solving both problems using RNNs. First, anomalies not labeled We are given a time series. If the anomalies are not labeled, we can train a GRU on the target of forecasting the next value in the time series. This process forces the GRU to learn a model of (recent) ‘normalcy’, adapting it along the way as ‘new normals’ develop. h(t) should model the ‘old normal’ at time t. h could be multi-dimensional. For example, one component could describe the mean value in the normal region, a second the trend. hnew(t) is similar to h(t) except that it is more heavily influenced by the recent values. For example, h(t) might behave as a slower moving average, hnew(t) as a faster one. Possibly with trend components so that we can discern if hnew(t)’s trend differs from h(t)’s. How can we nudge the GRU into learning that hnew(t) should model more recent values than does h(t)? We could learn the parameters in hnew(t)’s equation by explicitly forcing hnew(t) to forecast a short-horizon forecasting target. Such as y(t) to equal x(t-1), i.e. a one-step forecast. How can we make h(t) model a slower-adapting variant of hnew(t), i.e. model normalcy at a coarser time scale than does hnew(t)? (Except when we want h(t) to chase hnew(t) such as when a ‘new normal’ is developing.) A sensible way to force h(t) to move slower is to have it forecast a longer-horizon target, i.e. set y(t) to equal x(t-k) for sufficiently large k. While this is an appealing idea, the needed architecture is two forecasters on the same input at two different horizons. This is not what the GRU is. The GRU must learn all its parameters from a single target, say y(t) equal to x(t-1). Plus this doesn’t accommodate the exception, i.e. sometimes we want h(t) to chase h(t-1). We’d need another mechanism for this. To see what we have to work with in the GRU, let’s write out the state update equation again h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t) Assuming h(t-1) is slow-moving, and hnew(t) is very different from h(t-1), we’d want h(t) to chase h(t-1). We can make this happen by setting the components of u(t) to close to 0. But how? First let’s write out the update gate equation again u(t) = sigmoid(A*x(t) + B*h(t-1) + C) What if we modified it so that hnew(t-1) also appears on the right-hand side? This would in principle allow us to learn the behavior IF hnew(t) is very different from h(t-1) set u(t) close to 0else set u(t) close to 1 This also potentially helps the model adapt quicker to a developing ‘new normal’. Let’s illustrate this with an example. Consider a level shift, such as the one at the bolded value below. t: 1 2 3 4 5 6 7 8x: 1 1 1 1 4 4 4 4 hnew(5) is 4. h(4) is 1. So we’d want h(5) to stay close to 1. We interpret this as “we don’t know yet whether 4 is a transient anomaly or the being of a new normal, so let’s have our old normal adapt towards the new value but slowly”. As we continue moving to the right, h(t) will slowly start moving towards 4, i.e. towards hnew(t+1). This will in turn drive u(t) towards 1, which will further accelerate this movement, i.e. have a snowball effect. We can summarize this in the following behavior we expect on this level shift. At the level shift event, initially, the old model moves slowly as it doesn’t yet know it's a level shift. Once the evidence that it is indeed a level shift accumulates the model accelerates its move towards the new normal. On the other hand, if the shift was a transient anomaly (e.g. spike or dip), such as in the time series below t: 1 2 3 4 5 6 7 8x: 1 1 1 1 4 1 1 1 h would stay close to the old normal throughout. Feature Engineering What if we don’t like the idea of modifying the update gate equation? We might be able to achieve a similar effect by feature engineering. E.g. by working off a transformed version of the time series such as x(t)-x(t-1). The intuition here is that this time series reveals where the original time series changes more explicitly. A possibly more robust variant of this would be to define our featurized time series as a suitable faster-moving average minus a suitable slower-moving average. We can even imagine a sliding Kernel that explicitly distinguishes between transient changes and more stable ones. This Kernel function would have a high value if it is centered on an outlier deemed a transient event and low if not. Armed with such a Kernel, should we use it to generate the features or the labels? The former would mean that we are replacing the input x(t) by a feature-vector f(t) in which one of the features is the value of this Kernel function centered on t. The latter would mean that we set y(t) based on the value of this Kernel function at time t. We won’t dive into this question — just surface a few thoughts. It is appealing to use the Kernel function to generate the labels because they would then explicitly encode whether an event is transient or more persistent, exactly the right teaching signal for our anomaly-detecting GRU. On the other hand, we have to consider the risk that this labeling is biased. Generally speaking, label bias is more concerning than feature bias. Label bias manifests itself as “you are teaching the model the wrong thing”. Anomalies are labeled: Human or computer Now let’s delve into learning the GRU’s parameters when the anomalies are labeled by humans, computers, or a combination. In this section, by anomalies, we mean transient ones. We can use the labels to set u(t). IF x(t) is labeled ‘anomalous’ Set u(t) close to 0 // Direct GRU to continue 'old normal'ELSE Set u(t) close to 1 // Direct GRU to move towards 'most recent // values' Notice that we have taken direct control of the update gate here. Let’s look into Direct GRU to move towards ‘most recent values’ more closely. If the new values in the time series continue the old normal, then the update will also continue the old normal. If the new values are creating a different new normal, as in our level shift example, this will have the effect of the GRU adapting quickly to it. Okay, so this takes care of when to update the ‘normal’ and when not to. But what about how to update the two models— recent and more-recent — themselves? For the how it is tempting to rearrange the various mechanisms of the GRU for our use case. Sure, we lose the ability to use the GRU as a black-box. On the other hand, we learn what we can do with other combinations of these mechanisms. We will continue to use h(t), hnew(t) and u(t). h(t) and hnew(t) will each learn to forecast x(t) albeit at different horizons. So each will be equipped with its own target y(t) = x(t+k1) for h(t) and ynew(t) = x(t+k2) for hnew(t). u(t) will be set from the anomaly labels in the manner described earlier. This model may be viewed as blending self-supervised forecasting with supervised anomaly detection. What about the filter gate? What about the mechanism s(t) in the GRU? Can it be profitably used here? First, let’s remind ourselves what it actually does. It projects out those components of h(t-1), in the context of x(t), that matter to the task at hand. Which in our case is to detect anomalies. Well, actually under our hood we have two instances of another task: forecasting. As we have already used the update gate in the anomaly detection task (to switch between forecasting models), let’s try to use it inside a forecasting task itself. Forecasting and Filter Gate We seek a good forecast of x(t) at a certain horizon. Such a model maintains a state that describes the current ‘normalcy’. This is represented in a possibly multi-dimensional vector. Such as a two-dimensional vector where one dimension captures a smoothed estimate of the most recent value; the second the local estimated trend at that value. Here is a physical ‘motion’ analogy. Say we’d like to predict the future location of a point moving in a certain Euclidean space. Statistical estimates of the current location and the current velocity are helpful in this regard. In this setting, we can speculate how the filtering gate might come into play. Depending on the time series some features of the ‘normalcy’ state may perform better than others on our forecasting task. For a short horizon such as one-step, and for a time series that doesn’t have a nice linear trend (although it may have seasonalities), an estimate of the most recent value may be the best forecaster. For a time series with a durable linear trend and for a longer horizon, the local trend dimension of the ‘normalcy’ state may be very predictive. The reasoning of the previous paragraph starts getting stronger as we add more dimensions to the ‘normalcy’ state model. Such as for various seasonalities, or lags. Using s(t) can in principle select out those components of the normalcy state that matter to the task at hand. This plays a role similar to that of feature selection or pruning in predictive models. Such pruning often helps. This is known both theoretically and empirically. It forces the algorithm to learn models with a bias towards simplicity. Simple models generally generalize better. Occam’s razor. But how do we learn s(t)? Okay, so we think using s(t) can help. Let’s dig a bit deeper to see how we might learn what we hope s(t) can learn. We will illustrate this in a basic RNN for time series forecasting. From the input x(t) we extract certain features such as its value, i.e. x(t) itself, and lags x(t)-x(t-k) for k=1, 2, .... (In order to compute the lags we need to remember previous values of the time series.) Let v(t) denote x(t)’s feature vector. The state vector h(t) mirrors this feature vector. For example, h1(t) may model a smoothed version of x(t), h2(t) a smoothed version of x(t)-x(t-1), and so on. The state vector models the characteristics of values of the time series that help forecast its future values. Such as an estimate of the most recent value, an estimate of the most recent trend, and possibly the various seasonalities. The RNN may now be expressed as h(t) = f(h(t-1),v(t))y(t) = g(h(t)) We can set y(t)=x(t+h) as the target. That is, we seek an h-step forecast of the time series x. f specifies how to derive the new state vector h(t) from the combination of the previous state vector h(t-1) and the feature vector v(t) of the new value x(t). g specifies how to derive the forecast from the current state vector h(t). For example, if h(t) just has two features: a smoothed estimate of the current value and a smoothed estimate of the trend at it, we might just multiply the second with a parameter learned from the target (this is especially useful to get the influence from different horizons, such as h being small versus large) and add the first one to it. In equation form, this would be y(t) = h1(t) + b*h2(t) The second term on the right-hand side models a trend-based correction to the first term. Learning happens by propagating back the forecast error and adjusting the parameters implicit in g and f. So how should we inject s(t) into the mix? First, let’s drastically simplify. Let’s consider h(t) = a*h(t-1) + (1-a)*v(t) This is not so naive for forecasting. In fact, this is how forecasters based on exponential smoothing work. Here a is the only learnable parameter in f. Note that this approach also matches the role we had for h(t), to serve as a smoothed version of v(t). Now we are ready to inject s(t). h(t) = s(t) O h(t-1) + (1-s(t))o v(t) That is, hi(t) = si(t)*hi(t-1) + (1-si(t))*vi(t) This update rule is potentially richer as we now have component-level control over the state vector update. Effectively we have gained the ability to do soft feature selection during this process. GRU and The Vanishing Gradient Problem What about the vanishing gradient problem? Is the GRU more robust against it? We won’t answer this question definitively; rather we will give some tantalizing hints on what might be at play. Let’s first write out the state update equations of the GRU vs the basic RNN. h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t) (GRU)h(t) = sigmoid(A*h(t-1) + B*x(t) + C) (Basic RNN) What jumps out? The sigmoid in the second equation. From our earlier discussion on the vanishing gradient problem, it seems that sigmoid-like transfer functions are implicated. Squashing functions have a near-zero slope in their tails. This can aid in the error gradients vanishing rather quickly, as backpropagation through time back-propagates the error seen at the output multiple time segments in the reverse direction through the chain of these sigmoids. By contrast, the GRU’s state update equation does not use a squashing nonlinearity. Stacked RNNs Now that we understand the GRU and the basic RNN more deeply, let’s see a significant generalization. By Consider the state update function of an RNN h(t) = f(h(t-1),x(t)) In the ones we have seen so far (the basic RNN and the GRU), f(h,x) = S1(Whh*h + Wxh*x) We may read this as “h(t) is obtained from h(t-1) plus x(t) in a feedforward architecture with zero hidden layers”. A stacked RNN simply adds one or more hidden layers to this computation. That is, the state update function becomes ‘deep’. Not surprisingly, this makes the RNN architecture richer, often performing better on certain tasks. A stacked RNN unfolded in time looks like this Now, in addition to being deep in time, we are also deep in the state update function. We now have L functions f1, ..., fL with their own learnable parameters. We can write this as f(h(l),h(l-1),l) = S1(Whh(l)*h(l) + Wxh(l)*h(l-1)), l = 1 to L where h(0) denotes x. The state representation at time t itself is richer. h(t) = (h(0, t), h(1, t),..., h(L, t)). This may be viewed as a hierarchical representation of state in order of increasing coarseness. As in deep forward neural networks. Inference Next, we talk inference. That is, how we might use a trained RNN to answer various questions. We can run a sequence of words w1, w2, ..., wn-1 through a trained RNN and produce a probability distribution over the likely next word. Typically, we want more than this. We want the most likely extension of a certain length k of the given sequence. That is, we want wn, wn+1, ..., wn+k-1` = argmax wn, wn+1, ..., wn+k-1` P(wn, wn+1, ..., wn+k-1 | w1, w2, ..., wn-1) This inference problem is called the decoding problem. When k is 1, the solution is just the word with the highest probability in the RNN’s output vector after the RNN has processed the words w1, w2, ..., wn-1 sequentially as input. For the general case of k, the decoding problem is intractable. That is, we cannot hope to find the most likely extension efficiently. So we resort to heuristic methods. Greedy decoding One simple approach to finding a good extension of length k is to start by finding the highest-probability word in the output vector, inputting this word to the RNN (so that it outputs the probability distribution over the next word), finding the highest-probability word again, and repeating the process. This approach is called greedy because it makes the best local decision in every iteration. This approach can work well when, in every greedy step, adding the highest-probability word in the output vector moves us towards a globally optimal solution. As in the example below. Example: Consider a language model trained on national, state, and county park names. Consider x(1) = yellowstone. The greedy extension will be x^(2) = national. Not surprisingly, such a happy circumstance is not always the case. As in the example below. Example: Consider a language model trained from a multiset of organization names. Examples of organization names are Bank of America, Google, National Institutes of Health, ... The term multiset means that organization names may be repeated in this list. Now consider the problem of finding the most popular organization name in this list. The first step of the greedy method would pick bank or the or whichever word occurs most frequently in this list. The most popular organization name (say Google) may not start with this first word. Beam search As mentioned earlier, optimal decoding is in general intractable (NP-hard). There are many heuristic approaches that try to do better than greedy decoding, at varying costs of running time and memory requirements. Beam search has turned out to be an especially attractive one in sequence-to-sequence labeling use cases (especially language translation). So that is what we will describe here. Beam search keeps the k best prefix sequences. In every iteration it considers all possible 1-step extensions of these k prefixes, computes their probabilities, and forms a new list of the k best prefix sequences thus far. It keeps going until the goal is reached. In our scenario this would be when the extended sequence lengths are T. It then pulls out the highest-scoring sequence in its list of k candidates as the final answer. References Statistical Language Models. From simple to ++, with use cases... | by Arun JagotaCS 224D: Deep Learning for NLPNeural net language modelsUnderstanding LSTM Networks — colah’s blogExponential Smoothing Approaches In Time Series Forecasting | by Arun Jagota Statistical Language Models. From simple to ++, with use cases... | by Arun Jagota CS 224D: Deep Learning for NLP Neural net language models Understanding LSTM Networks — colah’s blog Exponential Smoothing Approaches In Time Series Forecasting | by Arun Jagota
[ { "code": null, "e": 421, "s": 171, "text": "In NLP, a language model is a probability distribution over sequences on an alphabet of tokens. A central problem in language modeling is to learn a language model from examples, such as a model of English sentences from a training set of sentences." }, { "code": null, "e": 464, "s": 421, "text": "Language models have many uses. Such as..." }, { "code": null, "e": 607, "s": 464, "text": "Suggest auto-completes: the user types a few characters (or words) on a web search engine or a smartphone and likely extensions are suggested." }, { "code": null, "e": 799, "s": 607, "text": "Recognize handwriting: An image-based recognition system augmented with a language model has improved accuracy. For instance, it can guess a word from its context even when it is not legible." }, { "code": null, "e": 920, "s": 799, "text": "Recognize speech: As in handwriting recognition, augmenting a speech system with a language model improves its accuracy." }, { "code": null, "e": 955, "s": 920, "text": "Detect and correct spelling errors" }, { "code": null, "e": 1076, "s": 955, "text": "Translate languages: To translate text from one language to another, it helps to have language models for the languages." }, { "code": null, "e": 1283, "s": 1076, "text": "In [1], we discussed statistical language models, a standard paradigm in the 1990s and earlier. In the past few decades, a new paradigm has emerged: neural language models. This is the subject of this post." }, { "code": null, "e": 1724, "s": 1283, "text": "Why neural language models over statistical ones? The short answer: they yield state-of-the-art accuracy with minimal human engineering. Why? The short answer is: due to a combination of two breakthroughs in recent decades — deep neural networks, and recurrent ones. (Exponential increases in computing power and availability of training data also helped tremendously.) Distributed representations, i.e. word embeddings, also played a role." }, { "code": null, "e": 1837, "s": 1724, "text": "In this post, we will cover recurrent neural networks (including deep ones) in the context of language modeling." }, { "code": null, "e": 2054, "s": 1837, "text": "We start with the master equations. These are the most important take-away equations in this post. Beyond defining the language modeling problem precisely, they also serve to frame various approaches to its solution." }, { "code": null, "e": 2228, "s": 2054, "text": "Let P(w1, w2, ..., wn) denote the probability of a sequence (w1, w2, ..., wn) of tokens. The aim of learning is to learn such probabilities from a training set of sequences." }, { "code": null, "e": 2463, "s": 2228, "text": "Consider the related problem of predicting the next token of a sequence. We model this as P(wn | w1, w2, ..., wn-1). Note that if we can accurately predict the probabilities P(wn | w1, w2, ..., wn-1), we can chain them together to get" }, { "code": null, "e": 2548, "s": 2463, "text": "P(w1, w2, ..., wn) = P(w1)*P(w2 | w1)*P(w3 | w1, w2)* ... *P(wn | w1, w2, ..., wn-1)" }, { "code": null, "e": 2805, "s": 2548, "text": "Most learning approaches target language modeling as the next token prediction problem. This is a problem of supervised learning. The input is (w1, w2, ..., wn-1). The output we seek is a probability distribution over the various values that wn could take." }, { "code": null, "e": 2990, "s": 2805, "text": "Note that the output is a fixed-length probability vector. (The dimensionality could be very high, though. Hundreds of thousands to millions for a language model on English sentences.)" }, { "code": null, "e": 3183, "s": 2990, "text": "The input is not a fixed-length vector. Its length, n, varies. In many use cases, n can often be large, in the 100s or even 1000s. This is the primary factor that makes this problem difficult." }, { "code": null, "e": 3632, "s": 3183, "text": "Statistical approaches to estimating P(wn | w1, w2, ..., wn-1) when n is large must make some assumptions. Without them the problem is intractable. Consider n = 101 and say the alphabet just has two symbols: 0 and 1. The minimal training set size to reliably estimate P(wn | w1, w2, ..., wn-1) is of the order 2100. This is because the input can be any one of those choices, and we want to be able to predict the next token reasonably in each case." }, { "code": null, "e": 3952, "s": 3632, "text": "The most widely-made assumption in statistical approaches is Markovian. Specifically, P(wn | w1, w2, ..., wn-1) is approximated by P(wn | wn-k, ..., wn-1). This assumes that the next token probabilities depend only on the last k tokens. Here k is fixed, often to a small number (2 or 3). See [1] for more on this topic." }, { "code": null, "e": 4107, "s": 3952, "text": "This vastly simplifies the problem. At the cost of not being able to model long-range influences. Here is an example, from [2], of a long-range influence." }, { "code": null, "e": 4256, "s": 4107, "text": "“Jane walked into the room. John walked in too. It was late in the day, and everyone was walking home after a long day at work. Jane said hi to ___”" }, { "code": null, "e": 4350, "s": 4256, "text": "The answer is John. This requires remembering the one occurrence of John about 25 words back." }, { "code": null, "e": 4384, "s": 4350, "text": "Another nice example is from [4]." }, { "code": null, "e": 4431, "s": 4384, "text": "I grew up in France ... I speak fluent French." }, { "code": null, "e": 4522, "s": 4431, "text": "Predicting French involves remembering France which may have occurred many sentences back." }, { "code": null, "e": 4808, "s": 4522, "text": "Neural language models address this “long-range influence” problem. Additionally, they also address the short-range influence problem better, specifically with automatically learnable feature vectors. (Statistical approaches can also use features; however, these are human-engineered.)" }, { "code": null, "e": 4836, "s": 4808, "text": "Early Neural Language Model" }, { "code": null, "e": 5104, "s": 4836, "text": "One of the early neural language models, as described in [3], is feedforward in nature. Whereas the more recent approaches are now all recurrent, we start with this model because it has some insightful characteristics that will set the stage for the ones that follow." }, { "code": null, "e": 5286, "s": 5104, "text": "As with many statistical language models, this model is kth-order Markovian. That is, for n greater than k, it assumes that P(wn | w1, w2, ..., wn-1) equals P(wn | wn-k, ..., wn-1)." }, { "code": null, "e": 5657, "s": 5286, "text": "It uses distributed representations for input words. Distributed representations, more recently also called word embeddings, go back to the 1980s. A distributed representation of a word maps it onto a d-dimensional numeric space. Distributed representations are learned by algorithms in ways that encourage semantically-related words to be near each other in this space." }, { "code": null, "e": 6000, "s": 5657, "text": "The intuition for using learned distributed representations is the hope that they pick up useful features of words involving semantic relateness. For example, if one sees Paris and France in the same text, this might help the model to make sensible inferences involving the context French, such as in our language example: I speak fluent ___." }, { "code": null, "e": 6297, "s": 6000, "text": "This model then concatenates the distributed representations of wn-k, ..., wn-1. This forms the input vector, of dimensionality k*d. Since we want the output to be a probability distribution over the entire lexicon of words, this network uses N output neurons, where N is the size of the lexicon." }, { "code": null, "e": 6594, "s": 6297, "text": "A hidden layer sits between the input and output layers. As in any other multilayer neural network, the hidden layer maps the input to a vector of features. (The neurons are sigmoid-like, specifically tanh.) This mapping is done via learnable weights from each input neuron to each hidden neuron." }, { "code": null, "e": 6862, "s": 6594, "text": "The mapping from the hidden layer to the output layer uses the softmax function. This is because we want the output to be a probability distribution over the output neurons. The softmax function is parametrized by weights, one per (hidden neuron, output neuron) pair." }, { "code": null, "e": 7198, "s": 6862, "text": "The parameters of this network are learned in the usual way, i.e. via backpropagation using stochastic gradient descent. The distributed representations of the various words can also be learned during this process. Alternatively, such distributed representations can be pre-learned in some other way (e.g. word2vec) and just used here." }, { "code": null, "e": 7474, "s": 7198, "text": "It is worth noting that when the size of the lexicon N is huge (say in the millions) the computations involving the output layer become the bottlenecks. This is because the predicted output on a particular input needs to be a probability distribution over the entire lexicon." }, { "code": null, "e": 7745, "s": 7474, "text": "A more serious limitation is that this network, just like typical statistical models, cannot model influences among words that are more than k units apart. In our John-Jane example, we would need k to be at least 25 for us to have any hope of making the right inference." }, { "code": null, "e": 8034, "s": 7745, "text": "Statistical models that explicitly compute P(wn | wn-k, ..., wn-1) require memory that grows exponentially with k. This neural network model scales better. It uses k*d*h + h*N parameters, where h is the number of hidden neurons. So the number of parameters increases only linearly with k." }, { "code": null, "e": 8060, "s": 8034, "text": "Recurrent Neural Networks" }, { "code": null, "e": 8305, "s": 8060, "text": "Recurrent neural networks are appealing for language modeling because they are not constrained by k. That is, in principle, they can learn arbitrarily long-range influences. That said, it does require some special engineering for them to do so." }, { "code": null, "e": 8483, "s": 8305, "text": "We’ll start by describing a basic RNN. We will see that it has difficulty learning long-range influences. We will then discuss modifications to this RNN to alleviate this issue." }, { "code": null, "e": 8493, "s": 8483, "text": "Basic RNN" }, { "code": null, "e": 8656, "s": 8493, "text": "As a black box, i.e. from the input-output interface, an RNN looks like a feedforward neural network at first glance. It inputs a vector x and outputs a vector y." }, { "code": null, "e": 8831, "s": 8656, "text": "There is a twist though. The RNN expects to receive, as input, a sequence of vectors x(1), ..., x(T), one vector at a time, and outputs a sequence of vectors y(1), ..., y(T)." }, { "code": null, "e": 9403, "s": 8831, "text": "The output y(t) at time t is influenced not only by x(t), rather by the entire sequence x(1), ..., x(t) of inputs received till then. This is what makes the RNN powerful. And the associated learning problem challenging. The RNN must carry state. Somehow it must summarize the history x(1), ..., x(t-1) into a state, which we will call h(t-1), from which it can predict y(t) well. When the input x(t) is presented, it first updates its state to h(t). In effect, x(t) becomes part of the history of the inputs it has seen. It then produces the output vector y(t) from h(t)." }, { "code": null, "e": 9433, "s": 9403, "text": "We can write this formally as" }, { "code": null, "e": 9469, "s": 9433, "text": "h(t) = f(h(t-1),x(t))y(t) = g(h(t))" }, { "code": null, "e": 9524, "s": 9469, "text": "In summary, the RNN may be viewed as having two parts:" }, { "code": null, "e": 9654, "s": 9524, "text": "A part that updates the state based on the current state and the new input.A part that transforms the current state to an output." }, { "code": null, "e": 9730, "s": 9654, "text": "A part that updates the state based on the current state and the new input." }, { "code": null, "e": 9785, "s": 9730, "text": "A part that transforms the current state to an output." }, { "code": null, "e": 9923, "s": 9785, "text": "Part 1 is reminiscent of finite-state automata in computer science. Part 1+Part 2 is a finite-state transducer in computer science terms." }, { "code": null, "e": 10195, "s": 9923, "text": "The state in an FSA may be viewed as a categorical variable. By contrast, the state in an RNN is a multi-dimensional vector. The latter facilitates compact distributed representations of states that can generalize well, a major advantage of modern neural representations." }, { "code": null, "e": 10404, "s": 10195, "text": "The icing on the cake (to put it mildly) is that both the state-change and the state-to-output behaviors of the RNN can be learned automatically from a training set of (input sequence, output sequence) pairs." }, { "code": null, "e": 10442, "s": 10404, "text": "The State-change and Output Functions" }, { "code": null, "e": 10579, "s": 10442, "text": "Following the usual neural network ‘design pattern’ inspired in part by biological neural networks and approved by statistics, we’ll use" }, { "code": null, "e": 10624, "s": 10579, "text": "f(h,x) = S1(Whh*h + Wxh*x)g(h) = S2(Why*h)" }, { "code": null, "e": 10720, "s": 10624, "text": "Here S1 and S2 are often sigmoid-shaped functions, typically the tanh or the logistic function." }, { "code": null, "e": 10968, "s": 10720, "text": "f(h,x) computes the next state as a linear combination of the current state and the next input pushed through the squashing function S1. g(h) computes the output as a linear transformation of the new state pushed through the squashing function S2." }, { "code": null, "e": 10994, "s": 10968, "text": "RNNs in Language Modeling" }, { "code": null, "e": 11149, "s": 10994, "text": "A fundamental use case of RNNs is in language modeling. Recall that in language modeling, our primary interest is in estimating P(wn | w1, w2, ..., wn-1)." }, { "code": null, "e": 11687, "s": 11149, "text": "A natural way to model this in an RNN is to model wn-1 as the input vector x(n-1), the history w1, w2, ..., wn-2 as the state vector h(n-1) and the output y(n-1) as a probability vector over the lexicon of words. For these purposes, it is natural to use the softmax function as the output function S2. Rather than a squashing function. S2(u) exponentiates each component of u and then normalizes the resulting vector to form a probability distribution. That is, it divides each exponentiated value by the sum of the exponentiated values." }, { "code": null, "e": 12272, "s": 11687, "text": "Structurally, this is analogous to the feedforward neural language model described earlier. The output dimensionality is N, the size of the lexicon. The input dimensionality is based on how words are represented. If words are represented locally, i.e. as a one-hot encoding, the input dimensionality is N. If words are represented in a distributed fashion, the input dimensionality is the dimensionality of this distributed representation. The state vector’s dimensionality is analogous to a hidden layer’s dimensionality, and controls the capacity of the corresponding feature space." }, { "code": null, "e": 12672, "s": 12272, "text": "A sequence of words w1, w2, ..., wn-1, wn may be turned into a training instance for this RNN-based language model. The sequence of inputs is x(1), ..., x(n-1), the sequence of vectors of the first n-1 words. The target output y(n-1) associated with this sequence is derived from the word wn. It’s the probability vector with all its mass concentrated on the dimension that corresponds to this word." }, { "code": null, "e": 13479, "s": 12672, "text": "Let’s pause to reflect on this. The output dimensionality is always N, as we are trying to learn a language model. This does have learning consequences as N is often very large. The input dimensionality may be distributed and compact or local and typically huge, i.e. N. There are trade-offs. A local representation imparts the model with a high capacity and is capable of making fine-grained distinctions. Each word has its own vector of weights to each hidden neuron. Models using distributed representations of words in the input layer are exponentially-more compact, may learn much faster, and potentially generalize better. They can leverage distributed representations that have already been learned by effective algorithms such as word2vec and enhancements, possibly from a huge corpus of documents." }, { "code": null, "e": 13488, "s": 13479, "text": "Learning" }, { "code": null, "e": 13837, "s": 13488, "text": "The learnable parameters are the matrices of weights Whh, Wxh, and Why inside the state transition and the output functions. Whh controls the influence of the current state vector on the next state vector, Wxh the influence of the next input vector on the next state vector, and Why the influence of the next state vector on the next output vector." }, { "code": null, "e": 13949, "s": 13837, "text": "To understand how learning happens, it helps to unfold the recurrent neural network in time, as depicted below." }, { "code": null, "e": 14261, "s": 13949, "text": "Now consider the input x(t) at time t along with its target output y(t). Keeping in mind that the mapping we seek to learn is really to output close to y(t) on the sequence of inputs x(1), x(2), ..., x(t) we can depict the situation as a multilayer feedforward neural network unfolded in time as depicted below." }, { "code": null, "e": 14442, "s": 14261, "text": "So we can use backpropagation to learn the weights inside the functions f and g. With a twist. All the f’s in the picture above must have the same weights. They are all the same f!" }, { "code": null, "e": 14541, "s": 14442, "text": "Okay, we can make this happen by summing up the changes to each weight in f across all the layers." }, { "code": null, "e": 15322, "s": 14541, "text": "One way to think of this is as follows. Let’s imagine we have two versions of the network: the constrained version (whose weights are shared as explained in the previous paragraph) and the unconstrained version which is a multi-layer neural network with no weight sharing, i.e., each instance of f has its own weights. Before the learning on the pair (x(t), y(t)), we’ll initialize each weight in the unconstrained version to the corresponding weight from the constrained version. We then run one iteration of online backpropagation (aka stochastic gradient descent) to update the weights on the unconstrained version. From these, we derive the new weights on the constrained version by taking, for each constrained weight, the average of the unconstrained weights that map to it." }, { "code": null, "e": 15720, "s": 15322, "text": "Well, all this sounds great in principle. However, note that the unfolded network can be very deep! So if there is a long-range influence, meaning that x(t-k) strongly influences y(t) for a large k (say k = 100), the back-propagated error signal may get very weak. This is because every instance in which the error is back-propagated through f attenuates the error since f is a squashing function." }, { "code": null, "e": 15803, "s": 15720, "text": "Let’s expand on the last sentence in the previous paragraph, in the setting below." }, { "code": null, "e": 16217, "s": 15803, "text": "To simplify the explanation, we use a feedforward neural network with two hidden layers. Plus the input and the output layer. All layers have a single neuron each. All layers except the input one have a sigmoidal transfer function. hi denotes the output of the neuron at layer i, and ni denotes the input to this neuron. So we have hi = s(ni) where s denotes the sigmoid function. We also have ni = w(i-1)*h(i-1)." }, { "code": null, "e": 16292, "s": 16217, "text": "Note that to simplify the notation h0 denotes the input and h3 the output." }, { "code": null, "e": 16550, "s": 16292, "text": "In this illustration, we will use the loss function L = 1⁄2 (y-h3)2. The backpropagation algorithm computes the gradient of L with respect to each weight wi (applying the chain rule when needed) to decide on the change to make to the weight. More precisely," }, { "code": null, "e": 16571, "s": 16550, "text": "Delta wi = -n*dL/dwi" }, { "code": null, "e": 16694, "s": 16571, "text": "Here n is the learning rate. The ‘-’ is there because we are doing gradient descent (since we want to minimize the error)." }, { "code": null, "e": 16763, "s": 16694, "text": "So now it comes down to computing dL/dwi for the various weights wi." }, { "code": null, "e": 16784, "s": 16763, "text": "Let’s start with w2." }, { "code": null, "e": 16803, "s": 16784, "text": "By the chain rule," }, { "code": null, "e": 16870, "s": 16803, "text": "dL/dw2 = (dL/dh3)*(dh3/dn3)*(dn3/dw2) = 2(y-h3)*s(n3)*(1-s(n3))*h2" }, { "code": null, "e": 17177, "s": 16870, "text": "Admittedly we are overloading notation a bit. In the above, h2, h3 and n3 denote both the variables (neurons) and their particular values on the input x = h0. We are also using the fact that the derivative of the sigmoid function ds/dn equals s(n)*(1-s(n)). Also that, for i > 0, dni/dw(i-1) equals h(i-1)." }, { "code": null, "e": 17249, "s": 17177, "text": "Similarly, with a slightly deeper application of the chain rule, we get" }, { "code": null, "e": 17309, "s": 17249, "text": "dL/dw1 = (dL/dh3)*(dh3/dn3)*(dn3/dh2)*(dh2/dn2)*(dn2/dw1) =" }, { "code": null, "e": 17354, "s": 17309, "text": "2(y-h3)*s(n3)*(1-s(n3))*w2*s(n2)*(1-s(n2)*h1" }, { "code": null, "e": 17488, "s": 17354, "text": "Now imagine adding more hidden layers to our network (keeping the topology and the transfer functions the same) and computing dL/dw0." }, { "code": null, "e": 17579, "s": 17488, "text": "dL/dw0 = 2(y-h(K))*s(nK)*(1-s(nK))*w(K-1)*s(n(K-1))*(1-s(n(K-1))*...*w1*s(n1)*(1-s(n1))*h0" }, { "code": null, "e": 17955, "s": 17579, "text": "Consider any one term s(ni)*(1-s(ni)). This product is always less than 1⁄4. Combining all such pairs in dL/dw0 produces a multiplicative factor whose value is less than (1⁄4)^K. In view of this, as K increases, dL/dw0 approaches 0 very very quickly. This is the vanishing gradient problem. This has a potentially disastrous consequence in our example. We may never learn w0." }, { "code": null, "e": 17976, "s": 17955, "text": "A Long-range Example" }, { "code": null, "e": 18273, "s": 17976, "text": "Next, let’s see a realistic example with long-range influences. We will use it to illustrate that learning such influences is the issue with basic RNNs, not the ability to represent them. This same example will also help illustrate the mechanisms of a more advanced RNN that alleviate this issue." }, { "code": null, "e": 18524, "s": 18273, "text": "We’d like to process a long sequence of English words and output a 1 if the word terrorist appears at least once, and 0 if not. Were terrorist to occur only once and very early on in the sequence, this event needs to be remembered until the very end." }, { "code": null, "e": 18841, "s": 18524, "text": "Why not just output a 1 immediately after terrorist is detected, else keep going? That would be tweaking the mechanisms of a general solution to this particular problem. This tweak would not generalize to the broader class of problems exhibiting long-range influences, of which this is just one illustrative example." }, { "code": null, "e": 19560, "s": 18841, "text": "The XOR example was used in the feedforward neural networks setting in exactly the same way. Viewed as a problem to solve, XOR is trivial. Just input two binary numbers and output the binary number that is their exclusive OR. However, viewed as an example to illustrate issues with certain feedforward architectures and to test improvements, it has turned out to be quite useful. The XOR is linearly inseparable. This is why classifiers capable of only linear discrimination fail. Indeed in the 1980s, the XOR was often used as a benchmark to test and demonstrate the learning ability of backpropagation in the setting of multi-layer perceptrons — feedforward neural networks with a hidden layer and sigmoidal neurons." }, { "code": null, "e": 19922, "s": 19560, "text": "Okay, back to our example. Let’s refine the problem description for our purposes here. The input x(1), ..., x(t) is a sequence of vectors where x(i) represents the ith word. The output y(t) is 1 if the word terrorist appears in this sequence and 0 if not. So the output is a binary sequence aligned with the input sequence and has a very simple structure: 0*1*." }, { "code": null, "e": 20106, "s": 19922, "text": "We will represent a word as a one-hot encoded vector. The vector’s dimensionality is the size of the lexicon. The bit corresponding to the word being represented is 1, the rest are 0." }, { "code": null, "e": 20445, "s": 20106, "text": "Now consider a basic RNN for this problem. Its input and output structure has already been specified. What about the state? Let’s set the state vector’s dimensionality to be the same as that of the input vector. We’d like hi(t) to be close to 1 if the word indexed by i was seen at least once among x(1), ..., x(t), and close to 0 if not." }, { "code": null, "e": 20508, "s": 20445, "text": "This is certainly feasible representationally, with the choice" }, { "code": null, "e": 20549, "s": 20508, "text": "hi(t) = sigmoid(a*hi(t-1) + b*xi(t) + c)" }, { "code": null, "e": 20710, "s": 20549, "text": "It is easy to choose a, b, and c, for example, a = b = 1 and c slightly negative, so that hi(t) is essentially an OR of hi(t-1) and xi(t). This is what we want." }, { "code": null, "e": 21018, "s": 20710, "text": "Once we have processed the entire sequence, we can simply set y(t) to hi(t), where i indexes the particular word we care about (in our case, terrorist). We can write this in the form y = g(W*h(t)) where g is a sigmoid. W is the vector whose ith position is sufficiently positive (e.g. 1) and the rest are 0." }, { "code": null, "e": 21367, "s": 21018, "text": "Now let’s look at this situation from the perspective of learning. Imagine that we have a training set of (document, label) pairs where label is 1 if a certain word appears somewhere in the document and 0 if not. We can assume that the labeling is consistent, i.e. this “certain word” is always the same. However, we are not told what that word is." }, { "code": null, "e": 21583, "s": 21367, "text": "So there are two issues here: (i) the learner must deduce which of the potentially millions of words best discriminates the two classes and (ii) learn only sequentially as described earlier in the basic RNN section." }, { "code": null, "e": 22218, "s": 21583, "text": "Focusing on (ii), backpropagation-through-time may need to propagate error gradients far back in time in many cases. Such gradients can vanish as discussed in an earlier section. The consequence of this is that if in most positive instances, the last occurrence of the “certain word” (in our example, terrorist) appears well before the last word in the document, the learner will not be able to establish the connection between this occurrence and the output is 1. If our positive instances are at least somewhat long documents, in most of them, the last occurrence of the word terrorist will indeed be well before the document’s end." }, { "code": null, "e": 22625, "s": 22218, "text": "Before closing this section, we’d like to add that now that we have opened the door to the labeling driving the learning, this problem becomes broader in its import. We can pose any binary classification problem on text this way, so long as we have a rich enough data set. It’s up to the recurrent neural network solution to figure out which words and which sequential structure helps to solve the problem." }, { "code": null, "e": 22895, "s": 22625, "text": "That said if one’s aim is to solve such a problem and if there isn’t a compelling case to be made for sequential learning, one should try non-recurrent binary classifier algorithms first. Such as feedforward neural networks, random forests, naive Bayes classifiers, ..." }, { "code": null, "e": 22922, "s": 22895, "text": "Gated Recurrent Unit (GRU)" }, { "code": null, "e": 23092, "s": 22922, "text": "We now turn our attention to more advanced recurrent neural networks, capable of capturing long-range influences. Two such networks in wide use are the LSTM and the GRU." }, { "code": null, "e": 23210, "s": 23092, "text": "We will describe the GRU as its mechanisms are simpler while remaining effective for capturing long-range influences." }, { "code": null, "e": 23480, "s": 23210, "text": "At a high level, the GRU works in the same fashion as a basic RNN. The input is a sequence of vectors presented one by one. The GRU maintains state, capturing some key aspect of what it has seen so far. This state combined with the next input determines the next state." }, { "code": null, "e": 23536, "s": 23480, "text": "The advancement comes in the state transition function." }, { "code": null, "e": 23617, "s": 23536, "text": "We’ll use the example we just introduced to build up the description of the GRU." }, { "code": null, "e": 23686, "s": 23617, "text": "Consider the state update function of the basic RNN for this example" }, { "code": null, "e": 23724, "s": 23686, "text": "h(t) = sigmoid(A*h(t-1) + B*x(t) + C)" }, { "code": null, "e": 24140, "s": 23724, "text": "The GRU will build up h(t) from h(t-1) and x(t) in a different way. It introduces the notion of a new memory hnew(t) derived from h(t-1) and x(t). The process of deriving this new memory from h(t-1) and x(t) has a mechanism that first runs each component of h(t-1) through a filtering gate. Think of this as letting the network selectively pay differing attention to different components of h(t-1) for this purpose." }, { "code": null, "e": 24308, "s": 24140, "text": "This filter, let’s call it si(t), takes on a value between 0 and 1. Filtering involves multiplying hi(t-1) by si(t). In vector notation we write this as s(t) o h(t-1)." }, { "code": null, "e": 24438, "s": 24308, "text": "The filtered version of h(t-1) is then linearly combined with x(t) and passed through a component-wise tanh. The full equation is" }, { "code": null, "e": 24485, "s": 24438, "text": "hnew(t) = tanh(A*x(t) + B*(s(t) o h(t-1)) + C)" }, { "code": null, "e": 24692, "s": 24485, "text": "The new memory is then combined with the old memory to form the updated memory, in a manner that will be described soon. By contrast, in the basic RNN, the updated memory is formed only from the old memory." }, { "code": null, "e": 24787, "s": 24692, "text": "What would be a good hnew(t) in our example? Let’s capture the desired behavior in pseudocode." }, { "code": null, "e": 24978, "s": 24787, "text": "IF i indexes terrorist and xi(t) is 1 hnew,i(t) = ~ 1IF i indexes terrorist and hi(t-1) is ~ 1 hnew,i(t) = ~ 1IF i indexes some other word hnew,i(t) = ~ 0ALL ELSE hnew,i(t) = ~ 0" }, { "code": null, "e": 25191, "s": 24978, "text": "hnew,i(t) is close to 0 for any word i other than terrorist. hnew,terrorist(t) is close to 1 if the new input x(t) is terrorist or if terrorist has been seen previously, in which case hi(t-1) would be close to 1." }, { "code": null, "e": 25263, "s": 25191, "text": "Can we choose the learning parameters to emulate this desired behavior?" }, { "code": null, "e": 25305, "s": 25263, "text": "First, we will set C to the vector of 0s." }, { "code": null, "e": 25464, "s": 25305, "text": "The THEN clause of the first IF can be executed via an appropriate choice of matrix A. Specifically, set Aii equal to 1 and all the rest of A’s elements to 0." }, { "code": null, "e": 25648, "s": 25464, "text": "The THEN clause of the second IF can be executed by choosing si(t) to be near 1 for i indexing terrorist and near 0 for the rest. Choose B as a matrix of positive values, e.g. all 1s." }, { "code": null, "e": 25772, "s": 25648, "text": "Under these conditions on A, B, and s(t), hnew,i(t) will be set near 0 when neither of the first two THEN clauses triggers." }, { "code": null, "e": 26116, "s": 25772, "text": "At this stage the reader might wonder, what have we really gained? If the last occurrence of the word terrorist appeared way before the current t, will not computing hnew,i(t) from the long chain of triggerings of the second THEN clause — the one whose antecedent is “i indexes terrorist and hi(t-1) is near 1” — have the same diluting effect." }, { "code": null, "e": 26348, "s": 26116, "text": "The reader is right to wonder this way. We have not yet completed the GRU’s description. Once we have all the mechanisms in place we will get a better sense of how they all come together to alleviate the vanishing gradient problem." }, { "code": null, "e": 26578, "s": 26348, "text": "The GRU uses a second gate, called the update gate, to control the relative contributions of the old and the new memories towards the updated memory. By contrast, the basic RNN derives the updated memory just from the old memory." }, { "code": null, "e": 26668, "s": 26578, "text": "Before diving into the update gate, let’s complete the description of the filtering gate." }, { "code": null, "e": 26692, "s": 26668, "text": "Filtering Gate Equation" }, { "code": null, "e": 26700, "s": 26692, "text": "This is" }, { "code": null, "e": 26738, "s": 26700, "text": "s(t) = sigmoid(D*x(t) + E*h(t-1) + F)" }, { "code": null, "e": 26851, "s": 26738, "text": "Here D, E, and F are the matrices and vectors of the learnable parameters that control the behavior of the gate." }, { "code": null, "e": 27092, "s": 26851, "text": "In our terrorist example, the behavior we sought from s(t) was to simply project out the value of hi(t-1), where i indexes the word terrorist. How well we can learn this behavior automatically from a training set is a whole different story." }, { "code": null, "e": 27140, "s": 27092, "text": "Example to illustrate the update gate mechanism" }, { "code": null, "e": 27235, "s": 27140, "text": "To build intuition about the update gate and the role it plays, a different example will help." }, { "code": null, "e": 27428, "s": 27235, "text": "We’d like to do anomaly detection in a time series using an RNN. We want the anomaly detector to not only detect anomalies but also adapt to new normals. Let’s illustrate this with an example." }, { "code": null, "e": 27495, "s": 27428, "text": "1, 2, 3, 2, 4, 2, 3, 2, 3, 23, 22, 25, 24, 22, 23, 24, 25, 21, ..." }, { "code": null, "e": 27962, "s": 27495, "text": "We process this time series from left to right. The value 23 is way outside the range of the values we have seen to this point, so we deem it anomalous. As we should. As we continue to process values to the right of this anomaly, we see that a new normal is developing. (Specifically, a level shift.) At some point soon the anomaly detector should adapt to this, and start treating it as the ‘normal’. For example, stop deeming values between 20 and 25 as anomalies." }, { "code": null, "e": 28393, "s": 27962, "text": "We’d also like to be able to control ‘at some point soon’ more finely by providing a labeled data set. By this, we mean that a time series comes labeled with which points are anomalous and which not. The RNN should be able to deduce, for any particular time series, how aggressively or conservatively we want to transition to the ‘new normal’. This would be the time-series specific behavior inferred from the historical labeling." }, { "code": null, "e": 28596, "s": 28393, "text": "One way to approach this is to train the RNN to forecast the next value in the time series. If the actual next value differs a lot from the forecasted next value then deem that value as being anomalous." }, { "code": null, "e": 28788, "s": 28596, "text": "RNNs are in principle suited to one-step forecasting because this problem is similar to learning a language model. In both cases, we want to predict the next input from the historical inputs." }, { "code": null, "e": 28954, "s": 28788, "text": "The model that the RNN learns during its incremental learning on the target of forecasting the next value may be interpreted as the current model of ‘normal values’." }, { "code": null, "e": 29380, "s": 28954, "text": "Now suppose that this RNN is a basic RNN. What happens when it encounters the first occurrence of 23. We hope it flags it as anomalous. What happens next? It incrementally trains on 23, as it would on any new value. The effect of this is that, as we see more values at this level, the model will gradually adjust to this new level. That is, it is building a ‘new normal’. So far so good. It is going in the direction we want." }, { "code": null, "e": 29818, "s": 29380, "text": "If this 23 was an outlier, i.e. a spike, not a level shift, the RNN would soon adjust back to the old normal. So all seems good. Let’s look at this more closely though. As the basic RNN is incapable of remembering the old normal (the one based on the values in the time series to the left of the first occurrence of 23) it must unlearn its accommodation of 23 towards an evolving new normal. Which in hindsight it can see was an anomaly." }, { "code": null, "e": 30602, "s": 29818, "text": "The GRU addresses this situation better. Just like the basic RNN, the GRU learns to adapt its ‘normal’ by forecasting the next value and adjusting its model based on the forecast error. Unlike the basic RNN, the GRU works with two models: one a slower evolving model, captured in h(t), the second a faster-evolving model, captured in hnew(t). In effect, the GRU can remember both the ‘old normal’ and a tentative ‘new normal’ at the same time. Its composite model is a combination of these two. This gives it the flexibility that should the ‘new normal’ later turn out to be a ‘false alarm’, i.e. an anomaly, it can just use the ‘old normal’. By contrast, the basic RNN would have to unlearn it. It also lets the GRU adapt quicker to the new normal in case it is not a ‘false alarm’." }, { "code": null, "e": 30655, "s": 30602, "text": "This behavior is summarized in the pseudocode below." }, { "code": null, "e": 30941, "s": 30655, "text": "Evolve two models, a slow one and a fast one, based on forecasting and feedback from forecasting errors.IF the new fast model is somehow deemed as capturing a transient phenomenon continue treating the 'old model' as the normalELSE evolve towards the 'new fast model' as the normal" }, { "code": null, "e": 30968, "s": 30941, "text": "Update Gate Usage Equation" }, { "code": null, "e": 31073, "s": 30968, "text": "Let’s call this gate u. ui(t) is between 0 and 1. The equation for the updated memory using this gate is" }, { "code": null, "e": 31117, "s": 31073, "text": "hi(t) = (1-ui(t))*hi(t-1) + ui(t)*hnew,i(t)" }, { "code": null, "e": 31147, "s": 31117, "text": "which, in vector notation, is" }, { "code": null, "e": 31189, "s": 31147, "text": "h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t)" }, { "code": null, "e": 31223, "s": 31189, "text": "Anomaly Detection Example Refined" }, { "code": null, "e": 31723, "s": 31223, "text": "Next, let’s refine the discussion on our anomaly detection example. We’ll use one-dimensional input and output vectors since we are working with a time series. For the state vector, we might consider a higher dimensionality. Whatever we feel is appropriate to capture the ‘normal’ characteristics of the recent values of the time series. For instance, if we wish to capture not only (a smoothed version) of the most recent value of the time series but also its trend, we might choose two dimensions." }, { "code": null, "e": 32148, "s": 31723, "text": "By choosing the dimensions of h and hnew with care, we can detect different types of anomalies. To detect point anomalies, two-dimensional state vectors may suffice. One dimension models the central tendency, e.g. mean or median, the second the dispersion, e.g. standard deviation or a more robust version. To, additionally, detect trend changes, we may want additional dimensions, ones that model characteristics of trends." }, { "code": null, "e": 32376, "s": 32148, "text": "Like h(t), hnew(t) is also a model of recent values. That said, as hinted by the name, hnew(t) is a model of even more recent values than h(t). For example, h(t) might be a slow-moving average and hnew(t) a fast-moving average." }, { "code": null, "e": 32749, "s": 32376, "text": "Now suppose the most recent values in the time series are anomalous. Let’s say we know this fact. That is, the anomalies are labeled. We can capture this in the value of the update gate u(t) where t is one of these anomalous time points. This gives us control over whether we want the most recent values (which we know are anomalous) to update our ‘normalcy’ model or not." }, { "code": null, "e": 33007, "s": 32749, "text": "For instance, we might not want to alter our ‘normalcy’ model if we are in the midst of an anomaly. We can make this happen by setting the components of u(t) close to 0. If we are in a ‘normal’ region we want our normalcy model to adapt quicker to the data." }, { "code": null, "e": 33028, "s": 33007, "text": "Update Gate Equation" }, { "code": null, "e": 33229, "s": 33028, "text": "We have seen how the update gate’s value is used in constructing the updated memory from the new memory and the old memory. But how is the update gate’s value itself calculated? This is done as below." }, { "code": null, "e": 33267, "s": 33229, "text": "u(t) = sigmoid(A*x(t) + B*h(t-1) + C)" }, { "code": null, "e": 33342, "s": 33267, "text": "Here A, B, and C are the matrices and vectors of the learnable parameters." }, { "code": null, "e": 33377, "s": 33342, "text": "Putting All the Equations Together" }, { "code": null, "e": 33525, "s": 33377, "text": "We have covered all the mechanisms inside the GRU. Let’s put all the equations together and review the end-to-end flow. At a single time t that is." }, { "code": null, "e": 33696, "s": 33525, "text": "s(t) = sigmoid(A*x(t) + B*h(t-1) + C)hnew(t) = tanh(D*x(t) + E*(s(t) o h(t-1)) + F)u(t) = sigmoid(G*x(t) + H*h(t-1) + I)h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t)" }, { "code": null, "e": 33809, "s": 33696, "text": "Let’s now walk through the end-to-end flow at a single time t. We assume that the learning has already happened." }, { "code": null, "e": 34402, "s": 33809, "text": "The new input x(t) arrives at time t. The RNN’s current memory state is h(t-1). First, from these two we compute the value s(t) of the filtering gate. Now we have what we need to compute the value hnew(t) of the new memory. So we do that. Next, we compute the update gate’s value u(t) from x(t) and h(t-1). Note that the equations for computing s(t) and u(t) have the same form. The differing behaviors arise from the different learned parameters. Finally, we compute the updated memory h(t) from the old memory h(t-1) and the new memory hnew(t) using the update gate u(t) to combine the two." }, { "code": null, "e": 34413, "s": 34402, "text": "“Learning”" }, { "code": null, "e": 34509, "s": 34413, "text": "The parameters to be learned are the matrices A, B, D, E, G, and H and the vectors C, F, and I." }, { "code": null, "e": 34821, "s": 34509, "text": "We have placed this section’s name in quotes intentionally. Rather than describe learning in the usual purely supervised way, we will just convey intuition on how the various mechanisms in the GRU might be learned from some combination of human-driven biasing and self-supervised or supervised machine learning." }, { "code": null, "e": 35091, "s": 34821, "text": "We will illustrate these in the anomaly detection example. In this illustration, we will be taking some liberties with the GRU. That is, we will tweak its mechanisms as appropriate. Our aim is to provide insights into the mechanisms and variations by way of an example." }, { "code": null, "e": 35146, "s": 35091, "text": "Two for one: Anomaly detection also solves forecasting" }, { "code": null, "e": 35583, "s": 35146, "text": "We think it's helpful to add that buried within the anomaly detection approach we describe below are certain time series forecasting tasks. We want to call this out here because, in the process of describing how to use the (somewhat tweaked) GRU to solve time series anomaly detection problems, we will also be implicitly covering how to solve time series forecasting problems. So you get insights into solving both problems using RNNs." }, { "code": null, "e": 35612, "s": 35583, "text": "First, anomalies not labeled" }, { "code": null, "e": 35878, "s": 35612, "text": "We are given a time series. If the anomalies are not labeled, we can train a GRU on the target of forecasting the next value in the time series. This process forces the GRU to learn a model of (recent) ‘normalcy’, adapting it along the way as ‘new normals’ develop." }, { "code": null, "e": 36053, "s": 35878, "text": "h(t) should model the ‘old normal’ at time t. h could be multi-dimensional. For example, one component could describe the mean value in the normal region, a second the trend." }, { "code": null, "e": 36322, "s": 36053, "text": "hnew(t) is similar to h(t) except that it is more heavily influenced by the recent values. For example, h(t) might behave as a slower moving average, hnew(t) as a faster one. Possibly with trend components so that we can discern if hnew(t)’s trend differs from h(t)’s." }, { "code": null, "e": 36608, "s": 36322, "text": "How can we nudge the GRU into learning that hnew(t) should model more recent values than does h(t)? We could learn the parameters in hnew(t)’s equation by explicitly forcing hnew(t) to forecast a short-horizon forecasting target. Such as y(t) to equal x(t-1), i.e. a one-step forecast." }, { "code": null, "e": 36823, "s": 36608, "text": "How can we make h(t) model a slower-adapting variant of hnew(t), i.e. model normalcy at a coarser time scale than does hnew(t)? (Except when we want h(t) to chase hnew(t) such as when a ‘new normal’ is developing.)" }, { "code": null, "e": 37335, "s": 36823, "text": "A sensible way to force h(t) to move slower is to have it forecast a longer-horizon target, i.e. set y(t) to equal x(t-k) for sufficiently large k. While this is an appealing idea, the needed architecture is two forecasters on the same input at two different horizons. This is not what the GRU is. The GRU must learn all its parameters from a single target, say y(t) equal to x(t-1). Plus this doesn’t accommodate the exception, i.e. sometimes we want h(t) to chase h(t-1). We’d need another mechanism for this." }, { "code": null, "e": 37428, "s": 37335, "text": "To see what we have to work with in the GRU, let’s write out the state update equation again" }, { "code": null, "e": 37470, "s": 37428, "text": "h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t)" }, { "code": null, "e": 37659, "s": 37470, "text": "Assuming h(t-1) is slow-moving, and hnew(t) is very different from h(t-1), we’d want h(t) to chase h(t-1). We can make this happen by setting the components of u(t) to close to 0. But how?" }, { "code": null, "e": 37712, "s": 37659, "text": "First let’s write out the update gate equation again" }, { "code": null, "e": 37750, "s": 37712, "text": "u(t) = sigmoid(A*x(t) + B*h(t-1) + C)" }, { "code": null, "e": 37828, "s": 37750, "text": "What if we modified it so that hnew(t-1) also appears on the right-hand side?" }, { "code": null, "e": 37883, "s": 37828, "text": "This would in principle allow us to learn the behavior" }, { "code": null, "e": 37974, "s": 37883, "text": "IF hnew(t) is very different from h(t-1) set u(t) close to 0else set u(t) close to 1" }, { "code": null, "e": 38095, "s": 37974, "text": "This also potentially helps the model adapt quicker to a developing ‘new normal’. Let’s illustrate this with an example." }, { "code": null, "e": 38162, "s": 38095, "text": "Consider a level shift, such as the one at the bolded value below." }, { "code": null, "e": 38213, "s": 38162, "text": "t: 1 2 3 4 5 6 7 8x: 1 1 1 1 4 4 4 4" }, { "code": null, "e": 38449, "s": 38213, "text": "hnew(5) is 4. h(4) is 1. So we’d want h(5) to stay close to 1. We interpret this as “we don’t know yet whether 4 is a transient anomaly or the being of a new normal, so let’s have our old normal adapt towards the new value but slowly”." }, { "code": null, "e": 38664, "s": 38449, "text": "As we continue moving to the right, h(t) will slowly start moving towards 4, i.e. towards hnew(t+1). This will in turn drive u(t) towards 1, which will further accelerate this movement, i.e. have a snowball effect." }, { "code": null, "e": 38967, "s": 38664, "text": "We can summarize this in the following behavior we expect on this level shift. At the level shift event, initially, the old model moves slowly as it doesn’t yet know it's a level shift. Once the evidence that it is indeed a level shift accumulates the model accelerates its move towards the new normal." }, { "code": null, "e": 39077, "s": 38967, "text": "On the other hand, if the shift was a transient anomaly (e.g. spike or dip), such as in the time series below" }, { "code": null, "e": 39128, "s": 39077, "text": "t: 1 2 3 4 5 6 7 8x: 1 1 1 1 4 1 1 1" }, { "code": null, "e": 39177, "s": 39128, "text": "h would stay close to the old normal throughout." }, { "code": null, "e": 39197, "s": 39177, "text": "Feature Engineering" }, { "code": null, "e": 39687, "s": 39197, "text": "What if we don’t like the idea of modifying the update gate equation? We might be able to achieve a similar effect by feature engineering. E.g. by working off a transformed version of the time series such as x(t)-x(t-1). The intuition here is that this time series reveals where the original time series changes more explicitly. A possibly more robust variant of this would be to define our featurized time series as a suitable faster-moving average minus a suitable slower-moving average." }, { "code": null, "e": 39920, "s": 39687, "text": "We can even imagine a sliding Kernel that explicitly distinguishes between transient changes and more stable ones. This Kernel function would have a high value if it is centered on an outlier deemed a transient event and low if not." }, { "code": null, "e": 40261, "s": 39920, "text": "Armed with such a Kernel, should we use it to generate the features or the labels? The former would mean that we are replacing the input x(t) by a feature-vector f(t) in which one of the features is the value of this Kernel function centered on t. The latter would mean that we set y(t) based on the value of this Kernel function at time t." }, { "code": null, "e": 40772, "s": 40261, "text": "We won’t dive into this question — just surface a few thoughts. It is appealing to use the Kernel function to generate the labels because they would then explicitly encode whether an event is transient or more persistent, exactly the right teaching signal for our anomaly-detecting GRU. On the other hand, we have to consider the risk that this labeling is biased. Generally speaking, label bias is more concerning than feature bias. Label bias manifests itself as “you are teaching the model the wrong thing”." }, { "code": null, "e": 40813, "s": 40772, "text": "Anomalies are labeled: Human or computer" }, { "code": null, "e": 40990, "s": 40813, "text": "Now let’s delve into learning the GRU’s parameters when the anomalies are labeled by humans, computers, or a combination. In this section, by anomalies, we mean transient ones." }, { "code": null, "e": 41025, "s": 40990, "text": "We can use the labels to set u(t)." }, { "code": null, "e": 41224, "s": 41025, "text": "IF x(t) is labeled ‘anomalous’ Set u(t) close to 0 // Direct GRU to continue 'old normal'ELSE Set u(t) close to 1 // Direct GRU to move towards 'most recent // values'" }, { "code": null, "e": 41290, "s": 41224, "text": "Notice that we have taken direct control of the update gate here." }, { "code": null, "e": 41628, "s": 41290, "text": "Let’s look into Direct GRU to move towards ‘most recent values’ more closely. If the new values in the time series continue the old normal, then the update will also continue the old normal. If the new values are creating a different new normal, as in our level shift example, this will have the effect of the GRU adapting quickly to it." }, { "code": null, "e": 41783, "s": 41628, "text": "Okay, so this takes care of when to update the ‘normal’ and when not to. But what about how to update the two models— recent and more-recent — themselves?" }, { "code": null, "e": 42020, "s": 41783, "text": "For the how it is tempting to rearrange the various mechanisms of the GRU for our use case. Sure, we lose the ability to use the GRU as a black-box. On the other hand, we learn what we can do with other combinations of these mechanisms." }, { "code": null, "e": 42252, "s": 42020, "text": "We will continue to use h(t), hnew(t) and u(t). h(t) and hnew(t) will each learn to forecast x(t) albeit at different horizons. So each will be equipped with its own target y(t) = x(t+k1) for h(t) and ynew(t) = x(t+k2) for hnew(t)." }, { "code": null, "e": 42326, "s": 42252, "text": "u(t) will be set from the anomaly labels in the manner described earlier." }, { "code": null, "e": 42426, "s": 42326, "text": "This model may be viewed as blending self-supervised forecasting with supervised anomaly detection." }, { "code": null, "e": 42454, "s": 42426, "text": "What about the filter gate?" }, { "code": null, "e": 42724, "s": 42454, "text": "What about the mechanism s(t) in the GRU? Can it be profitably used here? First, let’s remind ourselves what it actually does. It projects out those components of h(t-1), in the context of x(t), that matter to the task at hand. Which in our case is to detect anomalies." }, { "code": null, "e": 42970, "s": 42724, "text": "Well, actually under our hood we have two instances of another task: forecasting. As we have already used the update gate in the anomaly detection task (to switch between forecasting models), let’s try to use it inside a forecasting task itself." }, { "code": null, "e": 42998, "s": 42970, "text": "Forecasting and Filter Gate" }, { "code": null, "e": 43342, "s": 42998, "text": "We seek a good forecast of x(t) at a certain horizon. Such a model maintains a state that describes the current ‘normalcy’. This is represented in a possibly multi-dimensional vector. Such as a two-dimensional vector where one dimension captures a smoothed estimate of the most recent value; the second the local estimated trend at that value." }, { "code": null, "e": 43571, "s": 43342, "text": "Here is a physical ‘motion’ analogy. Say we’d like to predict the future location of a point moving in a certain Euclidean space. Statistical estimates of the current location and the current velocity are helpful in this regard." }, { "code": null, "e": 44120, "s": 43571, "text": "In this setting, we can speculate how the filtering gate might come into play. Depending on the time series some features of the ‘normalcy’ state may perform better than others on our forecasting task. For a short horizon such as one-step, and for a time series that doesn’t have a nice linear trend (although it may have seasonalities), an estimate of the most recent value may be the best forecaster. For a time series with a durable linear trend and for a longer horizon, the local trend dimension of the ‘normalcy’ state may be very predictive." }, { "code": null, "e": 44285, "s": 44120, "text": "The reasoning of the previous paragraph starts getting stronger as we add more dimensions to the ‘normalcy’ state model. Such as for various seasonalities, or lags." }, { "code": null, "e": 44690, "s": 44285, "text": "Using s(t) can in principle select out those components of the normalcy state that matter to the task at hand. This plays a role similar to that of feature selection or pruning in predictive models. Such pruning often helps. This is known both theoretically and empirically. It forces the algorithm to learn models with a bias towards simplicity. Simple models generally generalize better. Occam’s razor." }, { "code": null, "e": 44716, "s": 44690, "text": "But how do we learn s(t)?" }, { "code": null, "e": 44833, "s": 44716, "text": "Okay, so we think using s(t) can help. Let’s dig a bit deeper to see how we might learn what we hope s(t) can learn." }, { "code": null, "e": 44901, "s": 44833, "text": "We will illustrate this in a basic RNN for time series forecasting." }, { "code": null, "e": 45310, "s": 44901, "text": "From the input x(t) we extract certain features such as its value, i.e. x(t) itself, and lags x(t)-x(t-k) for k=1, 2, .... (In order to compute the lags we need to remember previous values of the time series.) Let v(t) denote x(t)’s feature vector. The state vector h(t) mirrors this feature vector. For example, h1(t) may model a smoothed version of x(t), h2(t) a smoothed version of x(t)-x(t-1), and so on." }, { "code": null, "e": 45545, "s": 45310, "text": "The state vector models the characteristics of values of the time series that help forecast its future values. Such as an estimate of the most recent value, an estimate of the most recent trend, and possibly the various seasonalities." }, { "code": null, "e": 45577, "s": 45545, "text": "The RNN may now be expressed as" }, { "code": null, "e": 45613, "s": 45577, "text": "h(t) = f(h(t-1),v(t))y(t) = g(h(t))" }, { "code": null, "e": 45709, "s": 45613, "text": "We can set y(t)=x(t+h) as the target. That is, we seek an h-step forecast of the time series x." }, { "code": null, "e": 45869, "s": 45709, "text": "f specifies how to derive the new state vector h(t) from the combination of the previous state vector h(t-1) and the feature vector v(t) of the new value x(t)." }, { "code": null, "e": 46318, "s": 45869, "text": "g specifies how to derive the forecast from the current state vector h(t). For example, if h(t) just has two features: a smoothed estimate of the current value and a smoothed estimate of the trend at it, we might just multiply the second with a parameter learned from the target (this is especially useful to get the influence from different horizons, such as h being small versus large) and add the first one to it. In equation form, this would be" }, { "code": null, "e": 46341, "s": 46318, "text": "y(t) = h1(t) + b*h2(t)" }, { "code": null, "e": 46431, "s": 46341, "text": "The second term on the right-hand side models a trend-based correction to the first term." }, { "code": null, "e": 46537, "s": 46431, "text": "Learning happens by propagating back the forecast error and adjusting the parameters implicit in g and f." }, { "code": null, "e": 46630, "s": 46537, "text": "So how should we inject s(t) into the mix? First, let’s drastically simplify. Let’s consider" }, { "code": null, "e": 46659, "s": 46630, "text": "h(t) = a*h(t-1) + (1-a)*v(t)" }, { "code": null, "e": 46812, "s": 46659, "text": "This is not so naive for forecasting. In fact, this is how forecasters based on exponential smoothing work. Here a is the only learnable parameter in f." }, { "code": null, "e": 46915, "s": 46812, "text": "Note that this approach also matches the role we had for h(t), to serve as a smoothed version of v(t)." }, { "code": null, "e": 46948, "s": 46915, "text": "Now we are ready to inject s(t)." }, { "code": null, "e": 46986, "s": 46948, "text": "h(t) = s(t) O h(t-1) + (1-s(t))o v(t)" }, { "code": null, "e": 46995, "s": 46986, "text": "That is," }, { "code": null, "e": 47035, "s": 46995, "text": "hi(t) = si(t)*hi(t-1) + (1-si(t))*vi(t)" }, { "code": null, "e": 47232, "s": 47035, "text": "This update rule is potentially richer as we now have component-level control over the state vector update. Effectively we have gained the ability to do soft feature selection during this process." }, { "code": null, "e": 47271, "s": 47232, "text": "GRU and The Vanishing Gradient Problem" }, { "code": null, "e": 47462, "s": 47271, "text": "What about the vanishing gradient problem? Is the GRU more robust against it? We won’t answer this question definitively; rather we will give some tantalizing hints on what might be at play." }, { "code": null, "e": 47540, "s": 47462, "text": "Let’s first write out the state update equations of the GRU vs the basic RNN." }, { "code": null, "e": 47643, "s": 47540, "text": "h(t) = (1-u(t)) o h(t-1) + u(t) o hnew(t) (GRU)h(t) = sigmoid(A*h(t-1) + B*x(t) + C) (Basic RNN)" }, { "code": null, "e": 48103, "s": 47643, "text": "What jumps out? The sigmoid in the second equation. From our earlier discussion on the vanishing gradient problem, it seems that sigmoid-like transfer functions are implicated. Squashing functions have a near-zero slope in their tails. This can aid in the error gradients vanishing rather quickly, as backpropagation through time back-propagates the error seen at the output multiple time segments in the reverse direction through the chain of these sigmoids." }, { "code": null, "e": 48187, "s": 48103, "text": "By contrast, the GRU’s state update equation does not use a squashing nonlinearity." }, { "code": null, "e": 48200, "s": 48187, "text": "Stacked RNNs" }, { "code": null, "e": 48305, "s": 48200, "text": "Now that we understand the GRU and the basic RNN more deeply, let’s see a significant generalization. By" }, { "code": null, "e": 48350, "s": 48305, "text": "Consider the state update function of an RNN" }, { "code": null, "e": 48372, "s": 48350, "text": "h(t) = f(h(t-1),x(t))" }, { "code": null, "e": 48433, "s": 48372, "text": "In the ones we have seen so far (the basic RNN and the GRU)," }, { "code": null, "e": 48460, "s": 48433, "text": "f(h,x) = S1(Whh*h + Wxh*x)" }, { "code": null, "e": 48576, "s": 48460, "text": "We may read this as “h(t) is obtained from h(t-1) plus x(t) in a feedforward architecture with zero hidden layers”." }, { "code": null, "e": 48800, "s": 48576, "text": "A stacked RNN simply adds one or more hidden layers to this computation. That is, the state update function becomes ‘deep’. Not surprisingly, this makes the RNN architecture richer, often performing better on certain tasks." }, { "code": null, "e": 48847, "s": 48800, "text": "A stacked RNN unfolded in time looks like this" }, { "code": null, "e": 49028, "s": 48847, "text": "Now, in addition to being deep in time, we are also deep in the state update function. We now have L functions f1, ..., fL with their own learnable parameters. We can write this as" }, { "code": null, "e": 49091, "s": 49028, "text": "f(h(l),h(l-1),l) = S1(Whh(l)*h(l) + Wxh(l)*h(l-1)), l = 1 to L" }, { "code": null, "e": 49113, "s": 49091, "text": "where h(0) denotes x." }, { "code": null, "e": 49338, "s": 49113, "text": "The state representation at time t itself is richer. h(t) = (h(0, t), h(1, t),..., h(L, t)). This may be viewed as a hierarchical representation of state in order of increasing coarseness. As in deep forward neural networks." }, { "code": null, "e": 49348, "s": 49338, "text": "Inference" }, { "code": null, "e": 49442, "s": 49348, "text": "Next, we talk inference. That is, how we might use a trained RNN to answer various questions." }, { "code": null, "e": 49710, "s": 49442, "text": "We can run a sequence of words w1, w2, ..., wn-1 through a trained RNN and produce a probability distribution over the likely next word. Typically, we want more than this. We want the most likely extension of a certain length k of the given sequence. That is, we want" }, { "code": null, "e": 49810, "s": 49710, "text": "wn, wn+1, ..., wn+k-1` = argmax wn, wn+1, ..., wn+k-1` P(wn, wn+1, ..., wn+k-1 | w1, w2, ..., wn-1)" }, { "code": null, "e": 50213, "s": 49810, "text": "This inference problem is called the decoding problem. When k is 1, the solution is just the word with the highest probability in the RNN’s output vector after the RNN has processed the words w1, w2, ..., wn-1 sequentially as input. For the general case of k, the decoding problem is intractable. That is, we cannot hope to find the most likely extension efficiently. So we resort to heuristic methods." }, { "code": null, "e": 50229, "s": 50213, "text": "Greedy decoding" }, { "code": null, "e": 50627, "s": 50229, "text": "One simple approach to finding a good extension of length k is to start by finding the highest-probability word in the output vector, inputting this word to the RNN (so that it outputs the probability distribution over the next word), finding the highest-probability word again, and repeating the process. This approach is called greedy because it makes the best local decision in every iteration." }, { "code": null, "e": 50811, "s": 50627, "text": "This approach can work well when, in every greedy step, adding the highest-probability word in the output vector moves us towards a globally optimal solution. As in the example below." }, { "code": null, "e": 50973, "s": 50811, "text": "Example: Consider a language model trained on national, state, and county park names. Consider x(1) = yellowstone. The greedy extension will be x^(2) = national." }, { "code": null, "e": 51066, "s": 50973, "text": "Not surprisingly, such a happy circumstance is not always the case. As in the example below." }, { "code": null, "e": 51604, "s": 51066, "text": "Example: Consider a language model trained from a multiset of organization names. Examples of organization names are Bank of America, Google, National Institutes of Health, ... The term multiset means that organization names may be repeated in this list. Now consider the problem of finding the most popular organization name in this list. The first step of the greedy method would pick bank or the or whichever word occurs most frequently in this list. The most popular organization name (say Google) may not start with this first word." }, { "code": null, "e": 51616, "s": 51604, "text": "Beam search" }, { "code": null, "e": 52009, "s": 51616, "text": "As mentioned earlier, optimal decoding is in general intractable (NP-hard). There are many heuristic approaches that try to do better than greedy decoding, at varying costs of running time and memory requirements. Beam search has turned out to be an especially attractive one in sequence-to-sequence labeling use cases (especially language translation). So that is what we will describe here." }, { "code": null, "e": 52442, "s": 52009, "text": "Beam search keeps the k best prefix sequences. In every iteration it considers all possible 1-step extensions of these k prefixes, computes their probabilities, and forms a new list of the k best prefix sequences thus far. It keeps going until the goal is reached. In our scenario this would be when the extended sequence lengths are T. It then pulls out the highest-scoring sequence in its list of k candidates as the final answer." }, { "code": null, "e": 52453, "s": 52442, "text": "References" }, { "code": null, "e": 52710, "s": 52453, "text": "Statistical Language Models. From simple to ++, with use cases... | by Arun JagotaCS 224D: Deep Learning for NLPNeural net language modelsUnderstanding LSTM Networks — colah’s blogExponential Smoothing Approaches In Time Series Forecasting | by Arun Jagota" }, { "code": null, "e": 52793, "s": 52710, "text": "Statistical Language Models. From simple to ++, with use cases... | by Arun Jagota" }, { "code": null, "e": 52824, "s": 52793, "text": "CS 224D: Deep Learning for NLP" }, { "code": null, "e": 52851, "s": 52824, "text": "Neural net language models" }, { "code": null, "e": 52894, "s": 52851, "text": "Understanding LSTM Networks — colah’s blog" } ]
How to create boxplot in base R without axes labels?
The boxplot can be created by using boxplot function in base R but the Y−axis labels are generated based on the vector we pass through the function. If we want to remove the axis labels then axes = FALSE argument can be used. For example, if we have a vector x then the boxplot for x without axes labels can be created by using boxplot(x,axes=FALSE). Live Demo Consider the below vector x and creating boxplot − set.seed(777) x<−rnorm(50000,41.5,3.7) boxplot(x) Creating the boxplot without Y−axis labels − boxplot(x,axes=FALSE) Let’s have a look at another example − Live Demo y<−rnorm(10,1,0.5) boxplot(y) Removing Y−axis labels − boxplot(y,axes=FALSE) We can do the same for multiple boxplots if the data is contained in a data frame.
[ { "code": null, "e": 1413, "s": 1062, "text": "The boxplot can be created by using boxplot function in base R but the Y−axis labels are generated based on the vector we pass through the function. If we want to remove the axis labels then axes = FALSE argument can be used. For example, if we have a vector x then the boxplot for x without axes labels can be created by using boxplot(x,axes=FALSE)." }, { "code": null, "e": 1424, "s": 1413, "text": " Live Demo" }, { "code": null, "e": 1475, "s": 1424, "text": "Consider the below vector x and creating boxplot −" }, { "code": null, "e": 1525, "s": 1475, "text": "set.seed(777)\nx<−rnorm(50000,41.5,3.7)\nboxplot(x)" }, { "code": null, "e": 1570, "s": 1525, "text": "Creating the boxplot without Y−axis labels −" }, { "code": null, "e": 1592, "s": 1570, "text": "boxplot(x,axes=FALSE)" }, { "code": null, "e": 1631, "s": 1592, "text": "Let’s have a look at another example −" }, { "code": null, "e": 1642, "s": 1631, "text": " Live Demo" }, { "code": null, "e": 1672, "s": 1642, "text": "y<−rnorm(10,1,0.5)\nboxplot(y)" }, { "code": null, "e": 1697, "s": 1672, "text": "Removing Y−axis labels −" }, { "code": null, "e": 1719, "s": 1697, "text": "boxplot(y,axes=FALSE)" }, { "code": null, "e": 1802, "s": 1719, "text": "We can do the same for multiple boxplots if the data is contained in a data frame." } ]
POJO vs Java Beans - GeeksforGeeks
29 Nov, 2021 POJO classes POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath. POJOs are used for increasing the readability and re-usability of a program. POJOs have gained the most acceptance because they are easy to write and understand. They were introduced in EJB 3.0 by Sun microsystems. A POJO should not: Extend prespecified classes, Ex: public class GFG extends javax.servlet.http.HttpServlet { ... } is not a POJO class.Implement prespecified interfaces, Ex: public class Bar implements javax.ejb.EntityBean { ... } is not a POJO class.Contain prespecified annotations, Ex: @javax.persistence.Entity public class Baz { ... } is not a POJO class. Extend prespecified classes, Ex: public class GFG extends javax.servlet.http.HttpServlet { ... } is not a POJO class. Implement prespecified interfaces, Ex: public class Bar implements javax.ejb.EntityBean { ... } is not a POJO class. Contain prespecified annotations, Ex: @javax.persistence.Entity public class Baz { ... } is not a POJO class. POJOs basically define an entity. Like in your program, if you want an Employee class, then you can create a POJO as follows: Java // Employee POJO class to represent entity Employeepublic class Employee{ // default field String name; // public field public String id; // private salary private double salary; //arg-constructor to initialize fields public Employee(String name, String id, double salary) { this.name = name; this.id = id; this.salary = salary; } // getter method for name public String getName() { return name; } // getter method for id public String getId() { return id; } // getter method for salary public Double getSalary() { return salary; }} The above example is a well-defined example of the POJO class. As you can see, there is no restriction on access-modifiers of fields. They can be private, default, protected, or public. It is also not necessary to include any constructor in it.POJO is an object which encapsulates Business Logic. The following image shows a working example of the POJO class. Controllers interact with your business logic which in turn interact with POJO to access the database. In this example, a database entity is represented by POJO. This POJO has the same members as the database entity. Java Beans Beans are special type of Pojos. There are some restrictions on POJO to be a bean. All JavaBeans are POJOs but not all POJOs are JavaBeans.Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens.Fields should be private. This is to provide complete control on fields.Fields should have getters or setters or both.A no-arg constructor should be there in a bean.Fields are accessed only by constructor or getter setters. All JavaBeans are POJOs but not all POJOs are JavaBeans. Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens. Fields should be private. This is to provide complete control on fields. Fields should have getters or setters or both. A no-arg constructor should be there in a bean. Fields are accessed only by constructor or getter setters. Getters and Setters have some special names depending on field name. For example, if field name is someProperty then its getter preferably will be: public "returnType" getSomeProperty() { return someProperty; } and setter will be public void setSomePRoperty(someProperty) { this.someProperty=someProperty; } Visibility of getters and setters is generally public. Getters and setters provide the complete restriction on fields. e.g. consider below the property, Integer age; If you set visibility of age to the public, then any object can use this. Suppose you want that age can’t be 0. In that case, you can’t have control. Any object can set it 0. But by using the setter method, you have control. You can have a condition in your setter method. Similarly, for the getter method if you want that if your age is 0 then it should return null, you can achieve this by using the getter method as in the following example: Java // Java program to illustrate JavaBeans class Bean { // private field property private Integer property; Bean() { // No-arg constructor } // setter method for property public void setProperty(Integer property) { if (property == 0) { // if property is 0 return return; } this.property=property; } // getter method for property public Integer getProperty() { if (property == 0) { // if property is 0 return null return null; } return property; } } // Class to test above bean public class GFG { public static void main(String[] args) { Bean bean = new Bean(); bean.setProperty(0); System.out.println("After setting to 0: " + bean.getProperty()); bean.setProperty(5); System.out.println("After setting to valid" + " value: " + bean.getProperty()); } } Output:- After setting to 0: null After setting to valid value: 5 POJO vs Java Bean POJO Java Bean Conclusion POJO classes and Beans both are used to define java objects to increase their readability and reusability. POJOs don’t have other restrictions while beans are special POJOs with some restrictions. This article is contributed by Vishal Garg. 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. rutvikatGFG PHANIX Sanan07 Ameya Gharpure anilkumarpal1 akshaysingh98088 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 23813, "s": 23785, "text": "\n29 Nov, 2021" }, { "code": null, "e": 23826, "s": 23813, "text": "POJO classes" }, { "code": null, "e": 24240, "s": 23826, "text": "POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special restriction other than those forced by the Java Language Specification and not requiring any classpath. POJOs are used for increasing the readability and re-usability of a program. POJOs have gained the most acceptance because they are easy to write and understand. They were introduced in EJB 3.0 by Sun microsystems." }, { "code": null, "e": 24259, "s": 24240, "text": "A POJO should not:" }, { "code": null, "e": 24602, "s": 24259, "text": "Extend prespecified classes, Ex: public class GFG extends javax.servlet.http.HttpServlet { ... } is not a POJO class.Implement prespecified interfaces, Ex: public class Bar implements javax.ejb.EntityBean { ... } is not a POJO class.Contain prespecified annotations, Ex: @javax.persistence.Entity public class Baz { ... } is not a POJO class." }, { "code": null, "e": 24720, "s": 24602, "text": "Extend prespecified classes, Ex: public class GFG extends javax.servlet.http.HttpServlet { ... } is not a POJO class." }, { "code": null, "e": 24837, "s": 24720, "text": "Implement prespecified interfaces, Ex: public class Bar implements javax.ejb.EntityBean { ... } is not a POJO class." }, { "code": null, "e": 24947, "s": 24837, "text": "Contain prespecified annotations, Ex: @javax.persistence.Entity public class Baz { ... } is not a POJO class." }, { "code": null, "e": 25073, "s": 24947, "text": "POJOs basically define an entity. Like in your program, if you want an Employee class, then you can create a POJO as follows:" }, { "code": null, "e": 25078, "s": 25073, "text": "Java" }, { "code": "// Employee POJO class to represent entity Employeepublic class Employee{ // default field String name; // public field public String id; // private salary private double salary; //arg-constructor to initialize fields public Employee(String name, String id, double salary) { this.name = name; this.id = id; this.salary = salary; } // getter method for name public String getName() { return name; } // getter method for id public String getId() { return id; } // getter method for salary public Double getSalary() { return salary; }}", "e": 25760, "s": 25078, "text": null }, { "code": null, "e": 26337, "s": 25760, "text": "The above example is a well-defined example of the POJO class. As you can see, there is no restriction on access-modifiers of fields. They can be private, default, protected, or public. It is also not necessary to include any constructor in it.POJO is an object which encapsulates Business Logic. The following image shows a working example of the POJO class. Controllers interact with your business logic which in turn interact with POJO to access the database. In this example, a database entity is represented by POJO. This POJO has the same members as the database entity." }, { "code": null, "e": 26348, "s": 26337, "text": "Java Beans" }, { "code": null, "e": 26431, "s": 26348, "text": "Beans are special type of Pojos. There are some restrictions on POJO to be a bean." }, { "code": null, "e": 26932, "s": 26431, "text": "All JavaBeans are POJOs but not all POJOs are JavaBeans.Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens.Fields should be private. This is to provide complete control on fields.Fields should have getters or setters or both.A no-arg constructor should be there in a bean.Fields are accessed only by constructor or getter setters." }, { "code": null, "e": 26989, "s": 26932, "text": "All JavaBeans are POJOs but not all POJOs are JavaBeans." }, { "code": null, "e": 27211, "s": 26989, "text": "Serializable i.e. they should implement Serializable interface. Still, some POJOs who don’t implement a Serializable interface are called POJOs because Serializable is a marker interface and therefore not of many burdens." }, { "code": null, "e": 27284, "s": 27211, "text": "Fields should be private. This is to provide complete control on fields." }, { "code": null, "e": 27331, "s": 27284, "text": "Fields should have getters or setters or both." }, { "code": null, "e": 27379, "s": 27331, "text": "A no-arg constructor should be there in a bean." }, { "code": null, "e": 27438, "s": 27379, "text": "Fields are accessed only by constructor or getter setters." }, { "code": null, "e": 27586, "s": 27438, "text": "Getters and Setters have some special names depending on field name. For example, if field name is someProperty then its getter preferably will be:" }, { "code": null, "e": 27653, "s": 27586, "text": "public \"returnType\" getSomeProperty()\n{\n return someProperty;\n} " }, { "code": null, "e": 27672, "s": 27653, "text": "and setter will be" }, { "code": null, "e": 27753, "s": 27672, "text": "public void setSomePRoperty(someProperty)\n{\n this.someProperty=someProperty;\n}" }, { "code": null, "e": 27906, "s": 27753, "text": "Visibility of getters and setters is generally public. Getters and setters provide the complete restriction on fields. e.g. consider below the property," }, { "code": null, "e": 27919, "s": 27906, "text": "Integer age;" }, { "code": null, "e": 28364, "s": 27919, "text": "If you set visibility of age to the public, then any object can use this. Suppose you want that age can’t be 0. In that case, you can’t have control. Any object can set it 0. But by using the setter method, you have control. You can have a condition in your setter method. Similarly, for the getter method if you want that if your age is 0 then it should return null, you can achieve this by using the getter method as in the following example:" }, { "code": null, "e": 28369, "s": 28364, "text": "Java" }, { "code": "// Java program to illustrate JavaBeans class Bean { // private field property private Integer property; Bean() { // No-arg constructor } // setter method for property public void setProperty(Integer property) { if (property == 0) { // if property is 0 return return; } this.property=property; } // getter method for property public Integer getProperty() { if (property == 0) { // if property is 0 return null return null; } return property; } } // Class to test above bean public class GFG { public static void main(String[] args) { Bean bean = new Bean(); bean.setProperty(0); System.out.println(\"After setting to 0: \" + bean.getProperty()); bean.setProperty(5); System.out.println(\"After setting to valid\" + \" value: \" + bean.getProperty()); } }", "e": 29417, "s": 28369, "text": null }, { "code": null, "e": 29427, "s": 29417, "text": "Output:- " }, { "code": null, "e": 29484, "s": 29427, "text": "After setting to 0: null\nAfter setting to valid value: 5" }, { "code": null, "e": 29502, "s": 29484, "text": "POJO vs Java Bean" }, { "code": null, "e": 29507, "s": 29502, "text": "POJO" }, { "code": null, "e": 29517, "s": 29507, "text": "Java Bean" }, { "code": null, "e": 29528, "s": 29517, "text": "Conclusion" }, { "code": null, "e": 29725, "s": 29528, "text": "POJO classes and Beans both are used to define java objects to increase their readability and reusability. POJOs don’t have other restrictions while beans are special POJOs with some restrictions." }, { "code": null, "e": 30145, "s": 29725, "text": "This article is contributed by Vishal Garg. 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": 30157, "s": 30145, "text": "rutvikatGFG" }, { "code": null, "e": 30164, "s": 30157, "text": "PHANIX" }, { "code": null, "e": 30172, "s": 30164, "text": "Sanan07" }, { "code": null, "e": 30187, "s": 30172, "text": "Ameya Gharpure" }, { "code": null, "e": 30201, "s": 30187, "text": "anilkumarpal1" }, { "code": null, "e": 30218, "s": 30201, "text": "akshaysingh98088" }, { "code": null, "e": 30223, "s": 30218, "text": "Java" }, { "code": null, "e": 30228, "s": 30223, "text": "Java" }, { "code": null, "e": 30326, "s": 30228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30335, "s": 30326, "text": "Comments" }, { "code": null, "e": 30348, "s": 30335, "text": "Old Comments" }, { "code": null, "e": 30399, "s": 30348, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 30429, "s": 30399, "text": "HashMap in Java with Examples" }, { "code": null, "e": 30460, "s": 30429, "text": "How to iterate any Map in Java" }, { "code": null, "e": 30492, "s": 30460, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 30511, "s": 30492, "text": "Interfaces in Java" }, { "code": null, "e": 30529, "s": 30511, "text": "ArrayList in Java" }, { "code": null, "e": 30561, "s": 30529, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30581, "s": 30561, "text": "Stack Class in Java" }, { "code": null, "e": 30605, "s": 30581, "text": "Singleton Class in Java" } ]
Overlapping Intervals | Practice | GeeksforGeeks
Given a collection of Intervals, the task is to merge all of the overlapping Intervals. Example 1: Input: Intervals = {{1,3},{2,4},{6,8},{9,10}} Output: {{1, 4}, {6, 8}, {9, 10}} Explanation: Given intervals: [1,3],[2,4] [6,8],[9,10], we have only two overlapping intervals here,[1,3] and [2,4]. Therefore we will merge these two and return [1,4], [6,8], [9,10]. Example 2: Input: Intervals = {{6,8},{1,9},{2,4},{4,7}} Output: {{1, 9}} Your Task: Complete the function overlappedInterval() that takes the list N intervals as input parameters and returns sorted list of intervals after merging. Expected Time Complexity: O(N*Log(N)). Expected Auxiliary Space: O(Log(N)) or O(N). Constraints: 1 ≤ N ≤ 100 0 ≤ x ≤ y ≤ 1000 0 roy99mustang This comment has been flagged for violating our community guidelines. 0 amanjugran12 days ago def overlappedInterval(self, Intervals): Intervals.sort(key=lambda x:x[0]) arr=[] i,j = 0,len(Intervals) while i<j: first = Intervals[i] if arr != []: nex = arr[-1] if first[0]<= nex[1]: arr[-1] = [nex[0],max(first[1],nex[1])] else: arr.append(first) else: arr.append(first) i+=1 return arr 0 ps271327131 week ago vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) { sort(intervals.begin(),intervals.end()); vector<vector<int>>v; int j=0; v.push_back(intervals[0]); for(int i=1;i<intervals.size();i++) { if(v[j][1]>=intervals[i][0]){ if(v[j][1]<intervals[i][1]) v[j][1]=intervals[i][1]; } else{ v.push_back(intervals[i]); j++;} } return v; } +1 aryansaini13101 week ago Simplest code: class Solution: def swap(self, arr): return arr[0] def overlappedInterval(self, arr): a=[] arr.sort(key=self.swap) temp=arr[0] for i in range(n): if arr[i][0]<=temp[1]: temp[1]=max(temp[1], arr[i][1]) else: a.append(temp) temp=arr[i] a.append(temp) return a 0 vishal10091 week ago vector<vector<int>> overlappedInterval(vector<vector<int>>& arr) { vector<vector<int>>res; sort(arr.begin(),arr.end()); int s=arr[0][0]; int e=arr[0][1]; for(int i=1;i<arr.size();i++){ if(arr[i][0]<=e){ e=max(e,arr[i][1]); } else{ res.push_back({s,e}); s=arr[i][0]; e=arr[i][1]; } } res.push_back({s,e}); return res; } 0 getkar1282 weeks ago def overlappedInterval(self, intervals): #Code here intervals.sort(key = lambda x: x[0]) output = [intervals[0]] for start, end in intervals[1: ]: lastEnd = output[-1][1] if start <= lastEnd: output[-1][1] = max(lastEnd, end) else: output.append([start, end]) return output 0 manjeetdhaterwal2 weeks ago public int[][] overlappedInterval(int[][] Intervals) { Arrays.sort(Intervals, (a, b)-> a[0]-b[0]); LinkedList<int[]> merged = new LinkedList<>(); for(int i=0; i<Intervals.length; i++) { if(merged.isEmpty() || merged.getLast()[1] < Intervals[i][0]) { merged.add(Intervals[i]); } else { merged.getLast()[1] = Math.max(merged.getLast()[1], Intervals[i][1]); } } int res[][] = new int[merged.size()][2]; return merged.toArray(res); } 0 manjeetdhaterwal This comment was deleted. 0 crawler2 weeks ago vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) { vector<vector<int>> result; sort(intervals.begin(), intervals.end()); if(intervals.size()) result.push_back(intervals[0]); for(int i = 1; i < intervals.size(); i++){ if(intervals[i][0] <= result[result.size()-1][1]){ int x = min(intervals[i][0], result[result.size()-1][0]); int y = max(intervals[i][1], result[result.size()-1][1]); result[result.size()-1][0] = x; result[result.size()-1][1] = y; } else result.push_back(intervals[i]); } return result; } +1 dip40122 weeks ago // C++ SOLUTION // Pls upvote if you think it is good public: vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) { sort(intervals.begin(),intervals.end()); vector<vector<int>> ans; vector<int> cur_interval(2); int n=intervals.size(); cur_interval=intervals[0]; for(int i=1; i<n; i++) { if(cur_interval[1]<intervals[i][0]) { ans.push_back(cur_interval); cur_interval=intervals[i]; } cur_interval[1]=max(cur_interval[1],intervals[i][1]); } ans.push_back(cur_interval); return ans; }}; 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": 326, "s": 238, "text": "Given a collection of Intervals, the task is to merge all of the overlapping Intervals." }, { "code": null, "e": 337, "s": 326, "text": "Example 1:" }, { "code": null, "e": 602, "s": 337, "text": "Input:\nIntervals = {{1,3},{2,4},{6,8},{9,10}}\nOutput: {{1, 4}, {6, 8}, {9, 10}}\nExplanation: Given intervals: [1,3],[2,4]\n[6,8],[9,10], we have only two overlapping\nintervals here,[1,3] and [2,4]. Therefore\nwe will merge these two and return [1,4],\n[6,8], [9,10].\n" }, { "code": null, "e": 613, "s": 602, "text": "Example 2:" }, { "code": null, "e": 675, "s": 613, "text": "Input:\nIntervals = {{6,8},{1,9},{2,4},{4,7}}\nOutput: {{1, 9}}" }, { "code": null, "e": 833, "s": 675, "text": "Your Task:\nComplete the function overlappedInterval() that takes the list N intervals as input parameters and returns sorted list of intervals after merging." }, { "code": null, "e": 917, "s": 833, "text": "Expected Time Complexity: O(N*Log(N)).\nExpected Auxiliary Space: O(Log(N)) or O(N)." }, { "code": null, "e": 959, "s": 917, "text": "Constraints:\n1 ≤ N ≤ 100\n0 ≤ x ≤ y ≤ 1000" }, { "code": null, "e": 961, "s": 959, "text": "0" }, { "code": null, "e": 974, "s": 961, "text": "roy99mustang" }, { "code": null, "e": 1044, "s": 974, "text": "This comment has been flagged for violating our community guidelines." }, { "code": null, "e": 1046, "s": 1044, "text": "0" }, { "code": null, "e": 1068, "s": 1046, "text": "amanjugran12 days ago" }, { "code": null, "e": 1493, "s": 1068, "text": "def overlappedInterval(self, Intervals): Intervals.sort(key=lambda x:x[0]) arr=[] i,j = 0,len(Intervals) while i<j: first = Intervals[i] if arr != []: nex = arr[-1] if first[0]<= nex[1]: arr[-1] = [nex[0],max(first[1],nex[1])] else: arr.append(first) else: arr.append(first) i+=1 return arr" }, { "code": null, "e": 1495, "s": 1493, "text": "0" }, { "code": null, "e": 1516, "s": 1495, "text": "ps271327131 week ago" }, { "code": null, "e": 2022, "s": 1516, "text": " vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) {\n sort(intervals.begin(),intervals.end());\n vector<vector<int>>v;\n int j=0; \n v.push_back(intervals[0]);\n for(int i=1;i<intervals.size();i++)\n {\n if(v[j][1]>=intervals[i][0]){\n if(v[j][1]<intervals[i][1])\n v[j][1]=intervals[i][1];\n }\n else{\n v.push_back(intervals[i]);\n j++;}\n }\n return v;\n }" }, { "code": null, "e": 2025, "s": 2022, "text": "+1" }, { "code": null, "e": 2050, "s": 2025, "text": "aryansaini13101 week ago" }, { "code": null, "e": 2065, "s": 2050, "text": "Simplest code:" }, { "code": null, "e": 2452, "s": 2065, "text": "class Solution: def swap(self, arr): return arr[0] def overlappedInterval(self, arr): a=[] arr.sort(key=self.swap) temp=arr[0] for i in range(n): if arr[i][0]<=temp[1]: temp[1]=max(temp[1], arr[i][1]) else: a.append(temp) temp=arr[i] a.append(temp) return a" }, { "code": null, "e": 2454, "s": 2452, "text": "0" }, { "code": null, "e": 2475, "s": 2454, "text": "vishal10091 week ago" }, { "code": null, "e": 2957, "s": 2475, "text": "vector<vector<int>> overlappedInterval(vector<vector<int>>& arr) {\n vector<vector<int>>res;\n sort(arr.begin(),arr.end());\n int s=arr[0][0];\n int e=arr[0][1];\n for(int i=1;i<arr.size();i++){\n if(arr[i][0]<=e){\n e=max(e,arr[i][1]);\n }\n else{\n res.push_back({s,e});\n s=arr[i][0];\n e=arr[i][1];\n }\n }\n res.push_back({s,e});\n return res;\n }" }, { "code": null, "e": 2959, "s": 2957, "text": "0" }, { "code": null, "e": 2980, "s": 2959, "text": "getkar1282 weeks ago" }, { "code": null, "e": 3307, "s": 2980, "text": "def overlappedInterval(self, intervals):\n \t#Code here\n \tintervals.sort(key = lambda x: x[0])\n \toutput = [intervals[0]]\n \t\n \tfor start, end in intervals[1: ]:\n \tlastEnd = output[-1][1]\n \tif start <= lastEnd:\n \toutput[-1][1] = max(lastEnd, end)\n \telse:\n \toutput.append([start, end])\n \t return output" }, { "code": null, "e": 3309, "s": 3307, "text": "0" }, { "code": null, "e": 3337, "s": 3309, "text": "manjeetdhaterwal2 weeks ago" }, { "code": null, "e": 3935, "s": 3337, "text": "public int[][] overlappedInterval(int[][] Intervals)\n {\n Arrays.sort(Intervals, (a, b)-> a[0]-b[0]);\n LinkedList<int[]> merged = new LinkedList<>();\n for(int i=0; i<Intervals.length; i++)\n {\n if(merged.isEmpty() || merged.getLast()[1] < Intervals[i][0])\n {\n merged.add(Intervals[i]);\n }\n else\n {\n merged.getLast()[1] = Math.max(merged.getLast()[1], Intervals[i][1]);\n }\n }\n int res[][] = new int[merged.size()][2];\n return merged.toArray(res);\n }" }, { "code": null, "e": 3937, "s": 3935, "text": "0" }, { "code": null, "e": 3954, "s": 3937, "text": "manjeetdhaterwal" }, { "code": null, "e": 3980, "s": 3954, "text": "This comment was deleted." }, { "code": null, "e": 3982, "s": 3980, "text": "0" }, { "code": null, "e": 4001, "s": 3982, "text": "crawler2 weeks ago" }, { "code": null, "e": 4726, "s": 4001, "text": " vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) {\n vector<vector<int>> result;\n sort(intervals.begin(), intervals.end());\n if(intervals.size())\n result.push_back(intervals[0]);\n for(int i = 1; i < intervals.size(); i++){\n if(intervals[i][0] <= result[result.size()-1][1]){\n int x = min(intervals[i][0], result[result.size()-1][0]);\n int y = max(intervals[i][1], result[result.size()-1][1]);\n result[result.size()-1][0] = x;\n result[result.size()-1][1] = y;\n }\n else\n result.push_back(intervals[i]);\n }\n return result;\n }" }, { "code": null, "e": 4729, "s": 4726, "text": "+1" }, { "code": null, "e": 4748, "s": 4729, "text": "dip40122 weeks ago" }, { "code": null, "e": 4764, "s": 4748, "text": "// C++ SOLUTION" }, { "code": null, "e": 4802, "s": 4764, "text": "// Pls upvote if you think it is good" }, { "code": null, "e": 5339, "s": 4804, "text": "public: vector<vector<int>> overlappedInterval(vector<vector<int>>& intervals) { sort(intervals.begin(),intervals.end()); vector<vector<int>> ans; vector<int> cur_interval(2); int n=intervals.size(); cur_interval=intervals[0]; for(int i=1; i<n; i++) { if(cur_interval[1]<intervals[i][0]) { ans.push_back(cur_interval); cur_interval=intervals[i]; } cur_interval[1]=max(cur_interval[1],intervals[i][1]); }" }, { "code": null, "e": 5401, "s": 5339, "text": " ans.push_back(cur_interval); return ans; }};" }, { "code": null, "e": 5547, "s": 5401, "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": 5583, "s": 5547, "text": " Login to access your submissions. " }, { "code": null, "e": 5593, "s": 5583, "text": "\nProblem\n" }, { "code": null, "e": 5603, "s": 5593, "text": "\nContest\n" }, { "code": null, "e": 5666, "s": 5603, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5814, "s": 5666, "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": 6022, "s": 5814, "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": 6128, "s": 6022, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python Functools – cached_property()
10 May, 2020 The @cached_property is a decorator which transforms a method of a class into a property whose value is computed only once and then cached as a normal attribute. Therefore, the cached result will be available as long as the instance will persist and we can use that method as an attribute of a class i.e Writing : instance.method Instead of : instance.method() cached_property is a part of functools module in Python. It is similar to property(), but cached_property() comes with an extra feature and that is caching. Note: For more information, refer to Functools module in Python The cache memory is a high-speed memory available inside CPU in order to speed up access to data and instructions. Therefore, the cache is a place that is quick to access. The result can be computed and stored once and from next time, the result can be accessed without recomputing it again. So, it is useful in case of expensive computations. Difference between @property and @cached_property: # Using @property # A sample classclass Sample(): def __init__(self): self.result = 50 @property # a method to increase the value of # result by 50 def increase(self): self.result = self.result + 50 return self.result # obj is an instance of the class sampleobj = Sample()print(obj.increase)print(obj.increase)print(obj.increase) OUTPUT 100 150 200 Same code but now we use @cached_property instead of @property # Using @cached_property from functools import cached_property # A sample classclass Sample(): def __init__(self): self.result = 50 @cached_property # a method to increase the value of # result by 50 def increase(self): self.result = self.result + 50 return self.result # obj is an instance of the class sampleobj = Sample()print(obj.increase)print(obj.increase)print(obj.increase) OUTPUT 100 100 100 You can clearly see that with @property the value of the result is computed each time the increase() method is called, that’s why it’s valued gets increased by 50. But with @cached_property, the value of the result is computed only once and then stored in the cache, so that it can be accessed each time the increase() method is called without recomputing the value of the result, and that’s why the output shows 100 every time. But how does it reduces the execution time and makes the program faster ?Consider the following example: # Without using @cached_property # A sample classclass Sample(): def __init__(self, lst): self.long_list = lst # a method to find the sum of the # given long list of integer values def find_sum(self): return (sum(self.long_list)) # obj is an instance of the class sample# the list can be longer, this is just# an exampleobj = Sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(obj.find_sum())print(obj.find_sum())print(obj.find_sum()) OUTPUT 55 55 55 Here, suppose if we pass a long list of values, the sum of the given list will be computed each time the find_sum() method is called, thereby taking much time for execution, and our program will ultimately become slow. What we want is that, since the list doesn’t change after the creation of the instance, so it would be nice, if the sum of the list is computed only once and not each time when we call the method and wish to access the sum. This can be achieved by using @cached_property Example: # With using @cached_property from functools import cached_property # A sample classclass Sample(): def __init__(self, lst): self.long_list = lst # a method to find the sum of the # given long list of integer values @cached_property def find_sum(self): return (sum(self.long_list)) # obj is an instance of the class sampleobj = Sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(obj.find_sum)print(obj.find_sum)print(obj.find_sum) OUTPUT 55 55 55 Though the output is the same, it reduces the execution time a lot. The sum of the list that is passed at the time of the creation of the instance is computed only once and stored in the cache memory and thereafter, it uses the same, already calculated value of the sum each time we call find_sum() method and saves us form expensive recomputations of the sum. Thus it reduces the execution time and makes our program faster. Python Decorators Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 332, "s": 28, "text": "The @cached_property is a decorator which transforms a method of a class into a property whose value is computed only once and then cached as a normal attribute. Therefore, the cached result will be available as long as the instance will persist and we can use that method as an attribute of a class i.e" }, { "code": null, "e": 393, "s": 332, "text": "Writing : instance.method\nInstead of : instance.method()\n" }, { "code": null, "e": 550, "s": 393, "text": "cached_property is a part of functools module in Python. It is similar to property(), but cached_property() comes with an extra feature and that is caching." }, { "code": null, "e": 614, "s": 550, "text": "Note: For more information, refer to Functools module in Python" }, { "code": null, "e": 958, "s": 614, "text": "The cache memory is a high-speed memory available inside CPU in order to speed up access to data and instructions. Therefore, the cache is a place that is quick to access. The result can be computed and stored once and from next time, the result can be accessed without recomputing it again. So, it is useful in case of expensive computations." }, { "code": null, "e": 1009, "s": 958, "text": "Difference between @property and @cached_property:" }, { "code": "# Using @property # A sample classclass Sample(): def __init__(self): self.result = 50 @property # a method to increase the value of # result by 50 def increase(self): self.result = self.result + 50 return self.result # obj is an instance of the class sampleobj = Sample()print(obj.increase)print(obj.increase)print(obj.increase)", "e": 1379, "s": 1009, "text": null }, { "code": null, "e": 1386, "s": 1379, "text": "OUTPUT" }, { "code": null, "e": 1399, "s": 1386, "text": "100\n150\n200\n" }, { "code": null, "e": 1462, "s": 1399, "text": "Same code but now we use @cached_property instead of @property" }, { "code": "# Using @cached_property from functools import cached_property # A sample classclass Sample(): def __init__(self): self.result = 50 @cached_property # a method to increase the value of # result by 50 def increase(self): self.result = self.result + 50 return self.result # obj is an instance of the class sampleobj = Sample()print(obj.increase)print(obj.increase)print(obj.increase)", "e": 1885, "s": 1462, "text": null }, { "code": null, "e": 1892, "s": 1885, "text": "OUTPUT" }, { "code": null, "e": 1905, "s": 1892, "text": "100\n100\n100\n" }, { "code": null, "e": 2334, "s": 1905, "text": "You can clearly see that with @property the value of the result is computed each time the increase() method is called, that’s why it’s valued gets increased by 50. But with @cached_property, the value of the result is computed only once and then stored in the cache, so that it can be accessed each time the increase() method is called without recomputing the value of the result, and that’s why the output shows 100 every time." }, { "code": null, "e": 2439, "s": 2334, "text": "But how does it reduces the execution time and makes the program faster ?Consider the following example:" }, { "code": "# Without using @cached_property # A sample classclass Sample(): def __init__(self, lst): self.long_list = lst # a method to find the sum of the # given long list of integer values def find_sum(self): return (sum(self.long_list)) # obj is an instance of the class sample# the list can be longer, this is just# an exampleobj = Sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(obj.find_sum())print(obj.find_sum())print(obj.find_sum())", "e": 2899, "s": 2439, "text": null }, { "code": null, "e": 2906, "s": 2899, "text": "OUTPUT" }, { "code": null, "e": 2916, "s": 2906, "text": "55\n55\n55\n" }, { "code": null, "e": 3406, "s": 2916, "text": "Here, suppose if we pass a long list of values, the sum of the given list will be computed each time the find_sum() method is called, thereby taking much time for execution, and our program will ultimately become slow. What we want is that, since the list doesn’t change after the creation of the instance, so it would be nice, if the sum of the list is computed only once and not each time when we call the method and wish to access the sum. This can be achieved by using @cached_property" }, { "code": null, "e": 3415, "s": 3406, "text": "Example:" }, { "code": "# With using @cached_property from functools import cached_property # A sample classclass Sample(): def __init__(self, lst): self.long_list = lst # a method to find the sum of the # given long list of integer values @cached_property def find_sum(self): return (sum(self.long_list)) # obj is an instance of the class sampleobj = Sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])print(obj.find_sum)print(obj.find_sum)print(obj.find_sum)", "e": 3872, "s": 3415, "text": null }, { "code": null, "e": 3879, "s": 3872, "text": "OUTPUT" }, { "code": null, "e": 3889, "s": 3879, "text": "55\n55\n55\n" }, { "code": null, "e": 4315, "s": 3889, "text": "Though the output is the same, it reduces the execution time a lot. The sum of the list that is passed at the time of the creation of the instance is computed only once and stored in the cache memory and thereafter, it uses the same, already calculated value of the sum each time we call find_sum() method and saves us form expensive recomputations of the sum. Thus it reduces the execution time and makes our program faster." }, { "code": null, "e": 4333, "s": 4315, "text": "Python Decorators" }, { "code": null, "e": 4340, "s": 4333, "text": "Python" } ]
Print all nodes less than a value x in a Min Heap.
19 Jun, 2022 Given a binary min heap and a value x, print all the binary heap nodes having value less than the given value x. Examples : Consider the below min heap as common input two both below examples. 2 / \ 3 15 / \ / \ 5 4 45 80 / \ / \ 6 150 77 120 Input : x = 15 Output : 2 3 5 6 4 Input : x = 80 Output : 2 3 5 6 4 77 15 45 The idea is to do a preorder traversal of the give Binary heap. While doing preorder traversal, if the value of a node is greater than the given value x, we return to the previous recursive call. Because all children nodes in a min heap are greater than the parent node. Otherwise we print current node and recur for its children. C++ Java C# Javascript // A C++ program to print all values// smaller than a given value in Binary// Heap#include <bits/stdc++.h>using namespace std; // A class for Min Heapclass MinHeap { // pointer to array of elements in heap int* harr; // maximum possible size of min heap int capacity; int heap_size; // Current no. of elements.public: // Constructor MinHeap(int capacity); // to heapify a subtree with root at // given index void MinHeapify(int); int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Inserts a new key 'k' void insertKey(int k); // Function to print all nodes smaller than k void printSmallerThan(int k, int pos);}; // Function to print all elements smaller than kvoid MinHeap::printSmallerThan(int x, int pos = 0){ /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } cout << harr[pos] << " "; printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos));} // Constructor: Builds a heap from a given// array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << "\nOverflow: Could not insertKey\n"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} // A recursive method to heapify a subtree with// root at given index. This method assumes that// the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }} // Driver program to test above functionsint main(){ MinHeap h(50); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x); return 0;} // A Java program to print all values// smaller than a given value in Binary// Heap // A class for Min Heapclass MinHeap { // array of elements in heap int[] harr; // maximum possible size of min heap int capacity; int heap_size; // Current no. of elements. int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Function to print all elements smaller than k void printSmallerThan(int x, int pos) { /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } System.out.print(harr[pos] + " "); printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos)); } // Constructor: Builds a heap of given size public MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' void insertKey(int k) { if (heap_size == capacity) { System.out.println("Overflow: Could not insertKey"); return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(i, parent(i)); i = parent(i); } } // A utility function to swap two elements void swap(int x, int y) { int temp = harr[x]; harr[x] = harr[y]; harr[y] = temp; } // Driver code public static void main(String[] args) { MinHeap h = new MinHeap(15); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x, 0); }}; // This code is contributed by shubham96301 // A C# program to print all values// smaller than a given value in// Binary Heapusing System; // A class for Min Heappublic class MinHeap{ // array of elements in heap int[] harr; // maximum possible size of min heap int capacity; // Current no. of elements int heap_size; int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Function to print // all elements smaller than k void printSmallerThan(int x, int pos) { /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } Console.Write(harr[pos] + " "); printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos)); } // Constructor: Builds a heap of given size public MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' void insertKey(int k) { if (heap_size == capacity) { Console.WriteLine("Overflow: Could not insertKey"); return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property // if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(i, parent(i)); i = parent(i); } } // A utility function to swap two elements void swap(int x, int y) { int temp = harr[x]; harr[x] = harr[y]; harr[y] = temp; } // Driver code public static void Main(String[] args) { MinHeap h = new MinHeap(15); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x, 0); }} // This code is contributed by PrinciRaj1992 <script> // A JavaScript program to print all values// smaller than a given value in Binary// Heap // A class for Min Heapclass MinHeap { // Constructor: Builds a heap of given size constructor(capacity){ this.harr = new Array(capacity); // array of elements in heap this.capacity = capacity; // maximum possible size of min heap this.heap_size = 0; // Current no. of elements. } parent(i) { return parseInt((i - 1) / 2); } left(i) { return (2 * i + 1); } right(i) { return (2 * i + 2); } // Function to print all elements smaller than k printSmallerThan(x, pos) { /* Make sure item exists */ if (pos >= this.heap_size) return; if (this.harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } document.write(this.harr[pos] , " "); this.printSmallerThan(x, this.left(pos)); this.printSmallerThan(x, this.right(pos)); } // A utility function to swap two elements swap(x, y) { let temp = this.harr[x]; this.harr[x] = this.harr[y]; this.harr[y] = temp; } // Inserts a new key 'k' insertKey(k) { if (this.heap_size == this.capacity) { System.out.println("Overflow: Could not insertKey"); return; } // First insert the new key at the end this.heap_size++; let i = this.heap_size - 1; this.harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && this.harr[this.parent(i)] > this.harr[i]) { this.swap(i, this.parent(i)); i = this.parent(i); } } } // Driver code let h = new MinHeap(15);h.insertKey(3);h.insertKey(2);h.insertKey(15);h.insertKey(5);h.insertKey(4);h.insertKey(45);h.insertKey(80);h.insertKey(6);h.insertKey(150);h.insertKey(77);h.insertKey(120); // Print all nodes smaller than 100.let x = 100;h.printSmallerThan(x, 0); // This code is contributed by Shinjan Patra </script> Output: 2 3 5 6 4 77 15 45 80 This article is contributed by Raghav 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. nobody_cares princiraj1992 shinjanpatra Heap Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Find k numbers with most occurrences in the given array Difference between Min Heap and Max Heap Priority queue of pairs in C++ (Ordered by first) K-th Largest Sum Contiguous Subarray Convert BST to Min Heap Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1 K maximum sum combinations from two arrays Fibonacci Heap | Set 1 (Introduction) Common operations on various Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jun, 2022" }, { "code": null, "e": 165, "s": 52, "text": "Given a binary min heap and a value x, print all the binary heap nodes having value less than the given value x." }, { "code": null, "e": 516, "s": 165, "text": "Examples : Consider the below min heap as\n common input two both below examples.\n 2\n / \\\n 3 15\n / \\ / \\\n 5 4 45 80\n / \\ / \\\n 6 150 77 120\n\nInput : x = 15 \nOutput : 2 3 5 6 4\n\nInput : x = 80\nOutput : 2 3 5 6 4 77 15 45" }, { "code": null, "e": 848, "s": 516, "text": "The idea is to do a preorder traversal of the give Binary heap. While doing preorder traversal, if the value of a node is greater than the given value x, we return to the previous recursive call. Because all children nodes in a min heap are greater than the parent node. Otherwise we print current node and recur for its children. " }, { "code": null, "e": 852, "s": 848, "text": "C++" }, { "code": null, "e": 857, "s": 852, "text": "Java" }, { "code": null, "e": 860, "s": 857, "text": "C#" }, { "code": null, "e": 871, "s": 860, "text": "Javascript" }, { "code": "// A C++ program to print all values// smaller than a given value in Binary// Heap#include <bits/stdc++.h>using namespace std; // A class for Min Heapclass MinHeap { // pointer to array of elements in heap int* harr; // maximum possible size of min heap int capacity; int heap_size; // Current no. of elements.public: // Constructor MinHeap(int capacity); // to heapify a subtree with root at // given index void MinHeapify(int); int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Inserts a new key 'k' void insertKey(int k); // Function to print all nodes smaller than k void printSmallerThan(int k, int pos);}; // Function to print all elements smaller than kvoid MinHeap::printSmallerThan(int x, int pos = 0){ /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } cout << harr[pos] << \" \"; printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos));} // Constructor: Builds a heap from a given// array a[] of given sizeMinHeap::MinHeap(int cap){ heap_size = 0; capacity = cap; harr = new int[cap];} // Inserts a new key 'k'void MinHeap::insertKey(int k){ if (heap_size == capacity) { cout << \"\\nOverflow: Could not insertKey\\n\"; return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(harr[i], harr[parent(i)]); i = parent(i); }} // A recursive method to heapify a subtree with// root at given index. This method assumes that// the subtrees are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l] < harr[i]) smallest = l; if (r < heap_size && harr[r] < harr[smallest]) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }} // Driver program to test above functionsint main(){ MinHeap h(50); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x); return 0;}", "e": 3446, "s": 871, "text": null }, { "code": "// A Java program to print all values// smaller than a given value in Binary// Heap // A class for Min Heapclass MinHeap { // array of elements in heap int[] harr; // maximum possible size of min heap int capacity; int heap_size; // Current no. of elements. int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Function to print all elements smaller than k void printSmallerThan(int x, int pos) { /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } System.out.print(harr[pos] + \" \"); printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos)); } // Constructor: Builds a heap of given size public MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' void insertKey(int k) { if (heap_size == capacity) { System.out.println(\"Overflow: Could not insertKey\"); return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(i, parent(i)); i = parent(i); } } // A utility function to swap two elements void swap(int x, int y) { int temp = harr[x]; harr[x] = harr[y]; harr[y] = temp; } // Driver code public static void main(String[] args) { MinHeap h = new MinHeap(15); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x, 0); }}; // This code is contributed by shubham96301", "e": 5621, "s": 3446, "text": null }, { "code": "// A C# program to print all values// smaller than a given value in// Binary Heapusing System; // A class for Min Heappublic class MinHeap{ // array of elements in heap int[] harr; // maximum possible size of min heap int capacity; // Current no. of elements int heap_size; int parent(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } // Function to print // all elements smaller than k void printSmallerThan(int x, int pos) { /* Make sure item exists */ if (pos >= heap_size) return; if (harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } Console.Write(harr[pos] + \" \"); printSmallerThan(x, left(pos)); printSmallerThan(x, right(pos)); } // Constructor: Builds a heap of given size public MinHeap(int cap) { heap_size = 0; capacity = cap; harr = new int[cap]; } // Inserts a new key 'k' void insertKey(int k) { if (heap_size == capacity) { Console.WriteLine(\"Overflow: Could not insertKey\"); return; } // First insert the new key at the end heap_size++; int i = heap_size - 1; harr[i] = k; // Fix the min heap property // if it is violated while (i != 0 && harr[parent(i)] > harr[i]) { swap(i, parent(i)); i = parent(i); } } // A utility function to swap two elements void swap(int x, int y) { int temp = harr[x]; harr[x] = harr[y]; harr[y] = temp; } // Driver code public static void Main(String[] args) { MinHeap h = new MinHeap(15); h.insertKey(3); h.insertKey(2); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); h.insertKey(80); h.insertKey(6); h.insertKey(150); h.insertKey(77); h.insertKey(120); // Print all nodes smaller than 100. int x = 100; h.printSmallerThan(x, 0); }} // This code is contributed by PrinciRaj1992", "e": 7867, "s": 5621, "text": null }, { "code": "<script> // A JavaScript program to print all values// smaller than a given value in Binary// Heap // A class for Min Heapclass MinHeap { // Constructor: Builds a heap of given size constructor(capacity){ this.harr = new Array(capacity); // array of elements in heap this.capacity = capacity; // maximum possible size of min heap this.heap_size = 0; // Current no. of elements. } parent(i) { return parseInt((i - 1) / 2); } left(i) { return (2 * i + 1); } right(i) { return (2 * i + 2); } // Function to print all elements smaller than k printSmallerThan(x, pos) { /* Make sure item exists */ if (pos >= this.heap_size) return; if (this.harr[pos] >= x) { /* Skip this node and its descendants, as they are all >= x . */ return; } document.write(this.harr[pos] , \" \"); this.printSmallerThan(x, this.left(pos)); this.printSmallerThan(x, this.right(pos)); } // A utility function to swap two elements swap(x, y) { let temp = this.harr[x]; this.harr[x] = this.harr[y]; this.harr[y] = temp; } // Inserts a new key 'k' insertKey(k) { if (this.heap_size == this.capacity) { System.out.println(\"Overflow: Could not insertKey\"); return; } // First insert the new key at the end this.heap_size++; let i = this.heap_size - 1; this.harr[i] = k; // Fix the min heap property if it is violated while (i != 0 && this.harr[this.parent(i)] > this.harr[i]) { this.swap(i, this.parent(i)); i = this.parent(i); } } } // Driver code let h = new MinHeap(15);h.insertKey(3);h.insertKey(2);h.insertKey(15);h.insertKey(5);h.insertKey(4);h.insertKey(45);h.insertKey(80);h.insertKey(6);h.insertKey(150);h.insertKey(77);h.insertKey(120); // Print all nodes smaller than 100.let x = 100;h.printSmallerThan(x, 0); // This code is contributed by Shinjan Patra </script>", "e": 9919, "s": 7867, "text": null }, { "code": null, "e": 9927, "s": 9919, "text": "Output:" }, { "code": null, "e": 9949, "s": 9927, "text": "2 3 5 6 4 77 15 45 80" }, { "code": null, "e": 10371, "s": 9949, "text": "This article is contributed by Raghav 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": 10384, "s": 10371, "text": "nobody_cares" }, { "code": null, "e": 10398, "s": 10384, "text": "princiraj1992" }, { "code": null, "e": 10411, "s": 10398, "text": "shinjanpatra" }, { "code": null, "e": 10416, "s": 10411, "text": "Heap" }, { "code": null, "e": 10421, "s": 10416, "text": "Heap" }, { "code": null, "e": 10519, "s": 10421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10551, "s": 10519, "text": "Introduction to Data Structures" }, { "code": null, "e": 10607, "s": 10551, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 10648, "s": 10607, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 10698, "s": 10648, "text": "Priority queue of pairs in C++ (Ordered by first)" }, { "code": null, "e": 10735, "s": 10698, "text": "K-th Largest Sum Contiguous Subarray" }, { "code": null, "e": 10759, "s": 10735, "text": "Convert BST to Min Heap" }, { "code": null, "e": 10834, "s": 10759, "text": "Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1" }, { "code": null, "e": 10877, "s": 10834, "text": "K maximum sum combinations from two arrays" }, { "code": null, "e": 10915, "s": 10877, "text": "Fibonacci Heap | Set 1 (Introduction)" } ]
Transactions and concurrency control - GeeksforGeeks
09 Oct, 2019 T1: read (P) ; read (Q) ; if P = 0 then Q : = Q + 1 ; write (Q) ; T2: read (Q) ; read (P) ; if Q = 0 then P : = P + 1 ; write (P) ; See http://www.geeksforgeeks.org/database-management-system-set-3/ 2 Phase Locking (2PL) is a concurrency control method that guarantees serializability. The protocol utilizes locks, applied by a transaction to data, which may block (interpreted as signals to stop) other transactions from accessing the same data during the transaction’s life. 2PL may be lead to deadlocks that result from the mutual blocking of two or more transactions. See the following situation, neither T3 nor T4 can make progress.Timestamp-based concurrency control algorithm is a non-lock concurrency control method. In Timestamp based method, deadlock cannot occur as no transaction ever waits. T1 can complete before T2 and T3 as there is no conflict between Write(X) of T1 and the operations in T2 and T3 which occur before Write(X) of T1 in the above diagram.T3 should can complete before T2 as the Read(Y) of T3 doesn’t conflict with Read(Y) of T2. Similarly, Write(X) of T3 doesn’t conflict with Read(Y) and Write(Y) operations of T2.Another way to solve this question is to create a dependency graph and topologically sort the dependency graph. After topologically sorting, we can see the sequence T1, T3, T2. T1: r1(X); r1(Z); w1(X); w1(Z) T2: r2(Y); r2(Z); w2(Z) T3: r3(Y); r3(X); w3(Y) S1: r1(X); r3(Y); r3(X); r2(Y); r2(Z); w3(Y); w2(Z); r1(Z); w1(X); w1(Z) S2: r1(X); r3(Y); r2(Y); r3(X); r1(Z); r2(Z); w3(Y); w1(X); w2(Z); w1(Z) 1. T1 start 2. T1 B old=12000 new=10000 3. T1 M old=0 new=2000 4. T1 commit 5. T2 start 6. T2 B old=10000 new=10500 7. T2 commit read(x); x := x – 50; write(x); read(y); y := y + 50; write(y) Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 31488, "s": 31460, "text": "\n09 Oct, 2019" }, { "code": null, "e": 31644, "s": 31488, "text": "T1: read (P) ;\n read (Q) ;\n if P = 0 then Q : = Q + 1 ;\n write (Q) ;\nT2: read (Q) ;\n read (P) ;\n if Q = 0 then P : = P + 1 ;\n write (P) ;" }, { "code": null, "e": 31711, "s": 31644, "text": "See http://www.geeksforgeeks.org/database-management-system-set-3/" }, { "code": null, "e": 32316, "s": 31711, "text": "2 Phase Locking (2PL) is a concurrency control method that guarantees serializability. The protocol utilizes locks, applied by a transaction to data, which may block (interpreted as signals to stop) other transactions from accessing the same data during the transaction’s life. 2PL may be lead to deadlocks that result from the mutual blocking of two or more transactions. See the following situation, neither T3 nor T4 can make progress.Timestamp-based concurrency control algorithm is a non-lock concurrency control method. In Timestamp based method, deadlock cannot occur as no transaction ever waits." }, { "code": null, "e": 32837, "s": 32316, "text": "T1 can complete before T2 and T3 as there is no conflict between Write(X) of T1 and the operations in T2 and T3 which occur before Write(X) of T1 in the above diagram.T3 should can complete before T2 as the Read(Y) of T3 doesn’t conflict with Read(Y) of T2. Similarly, Write(X) of T3 doesn’t conflict with Read(Y) and Write(Y) operations of T2.Another way to solve this question is to create a dependency graph and topologically sort the dependency graph. After topologically sorting, we can see the sequence T1, T3, T2." }, { "code": null, "e": 33071, "s": 32837, "text": "T1: r1(X); r1(Z); w1(X); w1(Z)\nT2: r2(Y); r2(Z); w2(Z)\nT3: r3(Y); r3(X); w3(Y)\nS1: r1(X); r3(Y); r3(X); r2(Y); r2(Z);\n w3(Y); w2(Z); r1(Z); w1(X); w1(Z)\nS2: r1(X); r3(Y); r2(Y); r3(X); r1(Z);\n r2(Z); w3(Y); w1(X); w2(Z); w1(Z) " }, { "code": null, "e": 33215, "s": 33071, "text": " 1. T1 start\n 2. T1 B old=12000 new=10000\n 3. T1 M old=0 new=2000\n 4. T1 commit\n 5. T2 start\n 6. T2 B old=10000 new=10500\n 7. T2 commit " }, { "code": null, "e": 33284, "s": 33215, "text": "read(x); x := x – 50; write(x); read(y); y := y + 50; write(y) " } ]
Maximum non-attacking Knights that can be placed on an N*M Chessboard
17 Sep, 2019 Given an N*M chessboard. The task is to find the maximum number of knights that can be placed on the given chessboard such that no knight attack some other knight. Example Input: N = 1, M = 4Output: 4Place a knight on every cell of the chessboard. Input: N = 4, M = 5Output: 10 Approach: As we know that a knight can attack in two ways. Here are the places which he can attack. Here, in the picture, the knight is on white color and attacks only the black color. Thus. we concluded that a knight can attack only on a different color.We can take help of this fact and use it for our purpose. Now as we know knight attacks on different color so we can keep all knights on the same color i.e. all on white or all on black. Thus making the highest number of knights which can be placed.To find the number of black or white, it is simply half of the total blocks on board. Total Blocks = n * mBlocks of the same color = (n * m) / 2 Corner cases: If there is only a single row or column. Then all the blocks can be filled by knights as a knight cannot attack in the same row or column. If there are only two rows or columns. Then every two columns (or rows) will be filled with knights and every consecutive two columns (or rows) will remain empty. As demonstrated in the picture. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum number of// knights that can be placed on the given// chessboard such that no two// knights attack each otherint max_knight(int n, int m){ // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (max(m, n) / 4) * 4; if (max(m, n) % 4 == 1) { c += 2; } else if (max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); }} // Driver codeint main(){ int n = 4, m = 5; cout << max_knight(n, m); return 0;} // Java implementation of the approach import java.io.*; class GFG { // Function to return the maximum number of // knights that can be placed on the given // chessboard such that no two // knights attack each other static int max_knight(int n, int m) { // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return Math.max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (Math.max(m, n) / 4) * 4; if (Math.max(m, n) % 4 == 1) { c += 2; } else if (Math.max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); } } // Driver code public static void main (String[] args) { int n = 4, m = 5; System.out.println (max_knight(n, m)); }} // This code is contributed by ajit # Python3 implementation of the approach # Function to return the maximum number of # knights that can be placed on the given # chessboard such that no two # knights attack each other def max_knight(n, m) : # Check for corner case #1 # If row or column is 1 if (m == 1 or n == 1) : # If yes, then simply print total blocks # which will be the max of row or column return max(m, n); # Check for corner case #2 # If row or column is 2 elif (m == 2 or n == 2) : # If yes, then simply calculate # consecutive 2 rows or columns c = 0; c = (max(m, n) // 4) * 4; if (max(m, n) % 4 == 1) : c += 2; elif (max(m, n) % 4 > 1) : c += 4; return c; # For general case, just print the # half of total blocks else : return (((m * n) + 1) // 2); # Driver code if __name__ == "__main__" : n = 4; m = 5; print(max_knight(n, m)); # This code is contributed by AnkitRai01 // C# implementation of the approach using System; class GFG{ // Function to return the maximum number of // knights that can be placed on the given // chessboard such that no two // knights attack each other static int max_knight(int n, int m) { // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return Math.Max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (Math.Max(m, n) / 4) * 4; if (Math.Max(m, n) % 4 == 1) { c += 2; } else if (Math.Max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); } } // Driver code static public void Main (){ int n = 4, m = 5; Console.Write(max_knight(n, m)); }} // This code is contributed by Tushil. 10 ankthon jit_t chessboard-problems Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph Understanding Time Complexity with Simple Examples What is Algorithm | Introduction to Algorithms Recursive Practice Problems with Solutions Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Sep, 2019" }, { "code": null, "e": 218, "s": 54, "text": "Given an N*M chessboard. The task is to find the maximum number of knights that can be placed on the given chessboard such that no knight attack some other knight." }, { "code": null, "e": 226, "s": 218, "text": "Example" }, { "code": null, "e": 302, "s": 226, "text": "Input: N = 1, M = 4Output: 4Place a knight on every cell of the chessboard." }, { "code": null, "e": 332, "s": 302, "text": "Input: N = 4, M = 5Output: 10" }, { "code": null, "e": 432, "s": 332, "text": "Approach: As we know that a knight can attack in two ways. Here are the places which he can attack." }, { "code": null, "e": 922, "s": 432, "text": "Here, in the picture, the knight is on white color and attacks only the black color. Thus. we concluded that a knight can attack only on a different color.We can take help of this fact and use it for our purpose. Now as we know knight attacks on different color so we can keep all knights on the same color i.e. all on white or all on black. Thus making the highest number of knights which can be placed.To find the number of black or white, it is simply half of the total blocks on board." }, { "code": null, "e": 981, "s": 922, "text": "Total Blocks = n * mBlocks of the same color = (n * m) / 2" }, { "code": null, "e": 995, "s": 981, "text": "Corner cases:" }, { "code": null, "e": 1134, "s": 995, "text": "If there is only a single row or column. Then all the blocks can be filled by knights as a knight cannot attack in the same row or column." }, { "code": null, "e": 1329, "s": 1134, "text": "If there are only two rows or columns. Then every two columns (or rows) will be filled with knights and every consecutive two columns (or rows) will remain empty. As demonstrated in the picture." }, { "code": null, "e": 1380, "s": 1329, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1384, "s": 1380, "text": "C++" }, { "code": null, "e": 1389, "s": 1384, "text": "Java" }, { "code": null, "e": 1397, "s": 1389, "text": "Python3" }, { "code": null, "e": 1400, "s": 1397, "text": "C#" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum number of// knights that can be placed on the given// chessboard such that no two// knights attack each otherint max_knight(int n, int m){ // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (max(m, n) / 4) * 4; if (max(m, n) % 4 == 1) { c += 2; } else if (max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); }} // Driver codeint main(){ int n = 4, m = 5; cout << max_knight(n, m); return 0;}", "e": 2463, "s": 1400, "text": null }, { "code": "// Java implementation of the approach import java.io.*; class GFG { // Function to return the maximum number of // knights that can be placed on the given // chessboard such that no two // knights attack each other static int max_knight(int n, int m) { // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return Math.max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (Math.max(m, n) / 4) * 4; if (Math.max(m, n) % 4 == 1) { c += 2; } else if (Math.max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); } } // Driver code public static void main (String[] args) { int n = 4, m = 5; System.out.println (max_knight(n, m)); }} // This code is contributed by ajit ", "e": 3674, "s": 2463, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum number of # knights that can be placed on the given # chessboard such that no two # knights attack each other def max_knight(n, m) : # Check for corner case #1 # If row or column is 1 if (m == 1 or n == 1) : # If yes, then simply print total blocks # which will be the max of row or column return max(m, n); # Check for corner case #2 # If row or column is 2 elif (m == 2 or n == 2) : # If yes, then simply calculate # consecutive 2 rows or columns c = 0; c = (max(m, n) // 4) * 4; if (max(m, n) % 4 == 1) : c += 2; elif (max(m, n) % 4 > 1) : c += 4; return c; # For general case, just print the # half of total blocks else : return (((m * n) + 1) // 2); # Driver code if __name__ == \"__main__\" : n = 4; m = 5; print(max_knight(n, m)); # This code is contributed by AnkitRai01", "e": 4710, "s": 3674, "text": null }, { "code": "// C# implementation of the approach using System; class GFG{ // Function to return the maximum number of // knights that can be placed on the given // chessboard such that no two // knights attack each other static int max_knight(int n, int m) { // Check for corner case #1 // If row or column is 1 if (m == 1 || n == 1) { // If yes, then simply print total blocks // which will be the max of row or column return Math.Max(m, n); } // Check for corner case #2 // If row or column is 2 else if (m == 2 || n == 2) { // If yes, then simply calculate // consecutive 2 rows or columns int c = 0; c = (Math.Max(m, n) / 4) * 4; if (Math.Max(m, n) % 4 == 1) { c += 2; } else if (Math.Max(m, n) % 4 > 1) { c += 4; } return c; } // For general case, just print the // half of total blocks else { return (((m * n) + 1) / 2); } } // Driver code static public void Main (){ int n = 4, m = 5; Console.Write(max_knight(n, m)); }} // This code is contributed by Tushil.", "e": 5899, "s": 4710, "text": null }, { "code": null, "e": 5903, "s": 5899, "text": "10\n" }, { "code": null, "e": 5911, "s": 5903, "text": "ankthon" }, { "code": null, "e": 5917, "s": 5911, "text": "jit_t" }, { "code": null, "e": 5937, "s": 5917, "text": "chessboard-problems" }, { "code": null, "e": 5948, "s": 5937, "text": "Algorithms" }, { "code": null, "e": 5959, "s": 5948, "text": "Algorithms" }, { "code": null, "e": 6057, "s": 5959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6082, "s": 6057, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 6131, "s": 6082, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 6169, "s": 6131, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 6237, "s": 6169, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 6288, "s": 6237, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 6335, "s": 6288, "text": "What is Algorithm | Introduction to Algorithms" }, { "code": null, "e": 6378, "s": 6335, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 6441, "s": 6378, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 6468, "s": 6441, "text": "How to Start Learning DSA?" } ]
PHP | hexdec( ) Function
07 Mar, 2018 Hexadecimal is a positional numeral system with a base of 16. It has sixteen distinct symbols, where the first nine symbols are 0–9 which represent values zero to nine, and the rest 6 symbols are A, B, C, D, E, F which represent values from ten to fifteen respectively. Since hexadecimal digit represents four binary digits, it allows a more human-friendly representation of binary-coded values and hence it is preferred over other number systems like binary and octal. The hexdec() function in PHP converts a hexadecimal number to a decimal number.The hexdec() function converts numbers that are too large to fit into the integer type, larger values are returned as a float in that case. If hexdec() encounters any non-hexadecimal characters, it ignores them. Syntax: hexdec($value) Parameters: The hexdec() function accepts a single parameter $value. It is the hexadecimal number whose decimal equivalent you want to calculate. Return Value: The hexdec() function in PHP returns the decimal equivalent of a hexadecimal number. Examples: Input : hexdec("5e") Output : 94 Input : hexdec("a") Output : 10 Input : hexdec("f1f1") Output : 61937 Input : hexdec("abc451") Output : 11256913 Below program illustrate the working of hexdec() in PHP: <?php echo hexdec("5e") . "\n";echo hexdec("a") . "\n";echo hexdec("f1f1") . "\n";echo hexdec("abc451") . "\n"; ?> Output: 94 10 61937 11256913 Important points to note : It converts a hexadecimal number to its decimal equivalent. It returns the values as float if the numbers are too large to be returned as integer type . The hexadecimal number system is one of the most popular and widely used number system these days. Reference:http://php.net/manual/en/function.hexdec.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Mar, 2018" }, { "code": null, "e": 498, "s": 28, "text": "Hexadecimal is a positional numeral system with a base of 16. It has sixteen distinct symbols, where the first nine symbols are 0–9 which represent values zero to nine, and the rest 6 symbols are A, B, C, D, E, F which represent values from ten to fifteen respectively. Since hexadecimal digit represents four binary digits, it allows a more human-friendly representation of binary-coded values and hence it is preferred over other number systems like binary and octal." }, { "code": null, "e": 789, "s": 498, "text": "The hexdec() function in PHP converts a hexadecimal number to a decimal number.The hexdec() function converts numbers that are too large to fit into the integer type, larger values are returned as a float in that case. If hexdec() encounters any non-hexadecimal characters, it ignores them." }, { "code": null, "e": 797, "s": 789, "text": "Syntax:" }, { "code": null, "e": 812, "s": 797, "text": "hexdec($value)" }, { "code": null, "e": 958, "s": 812, "text": "Parameters: The hexdec() function accepts a single parameter $value. It is the hexadecimal number whose decimal equivalent you want to calculate." }, { "code": null, "e": 1057, "s": 958, "text": "Return Value: The hexdec() function in PHP returns the decimal equivalent of a hexadecimal number." }, { "code": null, "e": 1067, "s": 1057, "text": "Examples:" }, { "code": null, "e": 1217, "s": 1067, "text": "Input : hexdec(\"5e\")\nOutput : 94\n\nInput : hexdec(\"a\")\nOutput : 10\n\nInput : hexdec(\"f1f1\")\nOutput : 61937\n\nInput : hexdec(\"abc451\")\nOutput : 11256913\n" }, { "code": null, "e": 1274, "s": 1217, "text": "Below program illustrate the working of hexdec() in PHP:" }, { "code": "<?php echo hexdec(\"5e\") . \"\\n\";echo hexdec(\"a\") . \"\\n\";echo hexdec(\"f1f1\") . \"\\n\";echo hexdec(\"abc451\") . \"\\n\"; ?>", "e": 1391, "s": 1274, "text": null }, { "code": null, "e": 1399, "s": 1391, "text": "Output:" }, { "code": null, "e": 1421, "s": 1399, "text": "94\n10\n61937\n11256913\n" }, { "code": null, "e": 1448, "s": 1421, "text": "Important points to note :" }, { "code": null, "e": 1508, "s": 1448, "text": "It converts a hexadecimal number to its decimal equivalent." }, { "code": null, "e": 1601, "s": 1508, "text": "It returns the values as float if the numbers are too large to be returned as integer type ." }, { "code": null, "e": 1700, "s": 1601, "text": "The hexadecimal number system is one of the most popular and widely used number system these days." }, { "code": null, "e": 1755, "s": 1700, "text": "Reference:http://php.net/manual/en/function.hexdec.php" }, { "code": null, "e": 1768, "s": 1755, "text": "PHP-function" }, { "code": null, "e": 1772, "s": 1768, "text": "PHP" }, { "code": null, "e": 1789, "s": 1772, "text": "Web Technologies" }, { "code": null, "e": 1793, "s": 1789, "text": "PHP" } ]
NLP | Wordlist Corpus
20 Feb, 2019 What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files. How to create wordlist corpus? WordListCorpusReader – It is one of the simplest CorpusReader classes. This class provides access to the files that contain list of words or one word per line Wordlist file can be a CSV file or a txt file having one word in each line. In our wordlist filewe have added : geeks for geeks welcomes you to nlp articles we have added : geeks for geeks welcomes you to nlp articles Two arguments to give directory path containing the files list of filenames Code #1 : Creating a wordlist corpus from nltk.corpus.reader import WordListCorpusReaderx = WordListCorpusReader('.', ['C:\\Users\\dell\\Desktop\\wordlist.txt'])x.words() x.fileids() Output : ['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles'] ['C:\\Users\\dell\\Desktop\\wordlist.txt'] Code #2 : Accessing raw. x.raw() from nltk.tokenize import line_tokenizeprint ("Wordlist : ", line_tokenize(x.raw())) Output : 'geeks\r\nfor\r\ngeeks\r\nwelcomes\r\nyou\r\nto\r\nnlp\r\narticles' Wordlist : ['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles'] Code #3 : Accessing Name Wordlist corpus # Accessing pre-defined wordlistfrom nltk.corpus import names print ("Path : ", names.fileids()) print ("\nNo. of female names : ", len(names.words('female.txt'))) print ("\nNo. of male names : ", len(names.words('male.txt'))) Output : Path : ['female.txt', 'male.txt'] No. of female names : 5001 No. of male names : 2943 Code #4 : Accessing English Wordlist corpus # Accessing pre-defined wordlistfrom nltk.corpus import words print ("File : ", words.fileids()) print ("\nNo. of female names : ", len(words.words('en-basic'))) print ("\nNo. of male names : ", len(words.words('en'))) Output : File : ['en', 'en-basic'] No. of female names : 850 No. of male names : 235886 Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Feb, 2019" }, { "code": null, "e": 222, "s": 28, "text": "What is a corpus?A corpus can be defined as a collection of text documents. It can be thought as just a bunch of text files in a directory, often alongside many other directories of text files." }, { "code": null, "e": 253, "s": 222, "text": "How to create wordlist corpus?" }, { "code": null, "e": 324, "s": 253, "text": "WordListCorpusReader – It is one of the simplest CorpusReader classes." }, { "code": null, "e": 412, "s": 324, "text": "This class provides access to the files that contain list of words or one word per line" }, { "code": null, "e": 570, "s": 412, "text": "Wordlist file can be a CSV file or a txt file having one word in each line. In our wordlist filewe have added : \ngeeks\nfor\ngeeks\nwelcomes\nyou\nto\nnlp\narticles" }, { "code": null, "e": 632, "s": 570, "text": "we have added : \ngeeks\nfor\ngeeks\nwelcomes\nyou\nto\nnlp\narticles" }, { "code": null, "e": 654, "s": 632, "text": "Two arguments to give" }, { "code": null, "e": 690, "s": 654, "text": "directory path containing the files" }, { "code": null, "e": 708, "s": 690, "text": "list of filenames" }, { "code": null, "e": 745, "s": 708, "text": "Code #1 : Creating a wordlist corpus" }, { "code": "from nltk.corpus.reader import WordListCorpusReaderx = WordListCorpusReader('.', ['C:\\\\Users\\\\dell\\\\Desktop\\\\wordlist.txt'])x.words() x.fileids()", "e": 892, "s": 745, "text": null }, { "code": null, "e": 901, "s": 892, "text": "Output :" }, { "code": null, "e": 1016, "s": 901, "text": "['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles']\n\n['C:\\\\Users\\\\dell\\\\Desktop\\\\wordlist.txt']\n" }, { "code": null, "e": 1041, "s": 1016, "text": "Code #2 : Accessing raw." }, { "code": "x.raw() from nltk.tokenize import line_tokenizeprint (\"Wordlist : \", line_tokenize(x.raw()))", "e": 1135, "s": 1041, "text": null }, { "code": null, "e": 1144, "s": 1135, "text": "Output :" }, { "code": null, "e": 1294, "s": 1144, "text": "'geeks\\r\\nfor\\r\\ngeeks\\r\\nwelcomes\\r\\nyou\\r\\nto\\r\\nnlp\\r\\narticles'\n\nWordlist : ['geeks', 'for', 'geeks', 'welcomes', 'you', 'to', 'nlp', 'articles']" }, { "code": null, "e": 1335, "s": 1294, "text": "Code #3 : Accessing Name Wordlist corpus" }, { "code": "# Accessing pre-defined wordlistfrom nltk.corpus import names print (\"Path : \", names.fileids()) print (\"\\nNo. of female names : \", len(names.words('female.txt'))) print (\"\\nNo. of male names : \", len(names.words('male.txt')))", "e": 1565, "s": 1335, "text": null }, { "code": null, "e": 1574, "s": 1565, "text": "Output :" }, { "code": null, "e": 1665, "s": 1574, "text": "Path : ['female.txt', 'male.txt']\n\nNo. of female names : 5001\n\nNo. of male names : 2943" }, { "code": null, "e": 1709, "s": 1665, "text": "Code #4 : Accessing English Wordlist corpus" }, { "code": "# Accessing pre-defined wordlistfrom nltk.corpus import words print (\"File : \", words.fileids()) print (\"\\nNo. of female names : \", len(words.words('en-basic'))) print (\"\\nNo. of male names : \", len(words.words('en')))", "e": 1931, "s": 1709, "text": null }, { "code": null, "e": 1940, "s": 1931, "text": "Output :" }, { "code": null, "e": 2024, "s": 1940, "text": "File : ['en', 'en-basic']\n\nNo. of female names : 850\n\nNo. of male names : 235886" }, { "code": null, "e": 2052, "s": 2024, "text": "Natural-language-processing" }, { "code": null, "e": 2064, "s": 2052, "text": "Python-nltk" }, { "code": null, "e": 2081, "s": 2064, "text": "Machine Learning" }, { "code": null, "e": 2088, "s": 2081, "text": "Python" }, { "code": null, "e": 2105, "s": 2088, "text": "Machine Learning" } ]
Minimum sum of two numbers formed from digits of an array
31 Mar, 2022 Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers. Examples : Input: [6, 8, 4, 5, 2, 3] Output: 604 The minimum sum is formed by numbers 358 and 246 Input: [5, 3, 0, 7, 4] Output: 82 The minimum sum is formed by numbers 35 and 047 A minimum number will be formed from set of digits when smallest digit appears at most significant position and next smallest digit appears at next most significant position ans so on..The idea is to sort the array in increasing order and build two numbers by alternating picking digits from the array. So first number is formed by digits present in odd positions in the array and second number is formed by digits from even positions in the array. Finally, we return the sum of first and second number.Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to find minimum sum of two numbers// formed from digits of the array.#include <bits/stdc++.h>using namespace std; // Function to find and return minimum sum of// two numbers formed from digits of the array.int solve(int arr[], int n){ // sort the array sort(arr, arr + n); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate digit // of input array if (i & 1) a = a*10 + arr[i]; else b = b*10 + arr[i]; } // return the sum return a + b;} // Driver codeint main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Sum is " << solve(arr, n); return 0;} // Java program to find minimum sum of two numbers// formed from digits of the array.import java.util.Arrays; class GFG { // Function to find and return minimum sum of // two numbers formed from digits of the array. static int solve(int arr[], int n) { // sort the array Arrays.sort(arr); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate // digit of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } //driver code public static void main (String[] args) { int arr[] = {6, 8, 4, 5, 2, 3}; int n = arr.length; System.out.print("Sum is " + solve(arr, n)); }} //This code is contributed by Anant Agarwal. # Python3 program to find minimum sum of two# numbers formed from digits of the array. # Function to find and return minimum sum of# two numbers formed from digits of the array.def solve(arr, n): # sort the array arr.sort() # let two numbers be a and b a = 0; b = 0 for i in range(n): # Fill a and b with every alternate # digit of input array if (i % 2 != 0): a = a * 10 + arr[i] else: b = b * 10 + arr[i] # return the sum return a + b # Driver codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print("Sum is ", solve(arr, n)) # This code is contributed by Anant Agarwal. // C# program to find minimum// sum of two numbers formed// from digits of the array.using System; class GFG{ // Function to find and return // minimum sum of two numbers // formed from digits of the array. static int solve(int []arr, int n) { // sort the array Array.Sort(arr); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate digit // of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } // Driver code public static void Main () { int []arr = {6, 8, 4, 5, 2, 3}; int n = arr.Length; Console.WriteLine("Sum is " + solve(arr, n)); }} // This code is contributed by Anant Agarwal. <?php// PHP program to find minimum// sum of two numbers formed// from digits of the array. // Function to find and return// minimum sum of two numbers// formed from digits of the array.function solve($arr, $n){ // sort the array sort($arr); sort($arr , $n); // let two numbers be a and b $a = 0; $b = 0; for ($i = 0; $i < $n; $i++) { // fill a and b with every // alternate digit of input array if ($i & 1) $a = $a * 10 + $arr[$i]; else $b = $b * 10 + $arr[$i]; } // return the sum return $a + $b;} // Driver code$arr = array(6, 8, 4, 5, 2, 3);$n = sizeof($arr);echo "Sum is " , solve($arr, $n); // This code is contributed by nitin mittal.?> <script> // Javascript program to find minimum sum of two numbers// formed from digits of the array. // Function to find and return minimum sum of // two numbers formed from digits of the array. function solve(arr, n) { // sort the array arr.sort(); // let two numbers be a and b let a = 0, b = 0; for (let i = 0; i < n; i++) { // fill a and b with every alternate // digit of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } // Driver Code let arr = [6, 8, 4, 5, 2, 3]; let n = arr.length; document.write("Sum is " + solve(arr, n)); </script> Output : Sum is 604 Method 2 (For Large Numbers) When we have to deal with very big numbers (as in the PRACTICE section of this question) the above approach will not work. The basic idea of approaching the question is the same as above, but instead of using numbers, we will use strings to handle sum. To add two numbers given in form of the string, you can refer to this. C++ Python3 Javascript #include <bits/stdc++.h>using namespace std; string solve(int arr[], int n){ // code here // sorting of array O(nlogn) sort(arr, arr + n); // Two String for storing our two minimum numbers string a = "", b = ""; // string string alternatively for (int i = 0; i < n; i += 2) { a += (arr[i] + '0'); } for (int i = 1; i < n; i += 2) { b += (arr[i] + '0'); } int j = a.length() - 1; int k = b.length() - 1; // as initial carry is zero int carry = 0; string ans = ""; while (j >= 0 && k >= 0) { int sum = 0; sum += (a[j] - '0') + (b[k] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; j--; k--; } // if string b is over and string a is left // here we dont need to put here while condition // as it would run at max one time. Because the difference // between both the strings could be at max 1. while (j >= 0) { int sum = 0; sum += (a[j] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; j--; } // if string a is over and string b is left while (k >= 0) { int sum = 0; sum += (b[k] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; k--; } // if carry is left if (carry) { ans += to_string(carry); } // to remove leading zeroes as they will be ahead of our sum while (!ans.empty() and ans.back() == '0') ans.pop_back(); // reverse our final string because we were storing sum from left to right reverse(ans.begin(), ans.end()); return ans;} // Driver Code Starts.int main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum is " << solve(arr, n); return 0;} // Driver Code Ends # Python code for the approachdef solve(arr, n): # sorting of array O(nlogn) arr.sort() # Two String for storing our two minimum numbers a,b = "","" # string string alternatively for i in range(0,n,2): a += str(arr[i]) for i in range(1,n,2): b += str(arr[i]) j = len(a) - 1 k = len(b) - 1 # as initial carry is zero carry = 0 ans = "" while (j >= 0 and k >= 0): sum = 0 sum += (ord(a[j]) - ord('0') + ord(b[k]) - ord('0')) + carry ans += str(sum % 10) carry = sum // 10 j -= 1 k -= 1 # if string b is over and string a is left # here we dont need to put here while condition # as it would run at max one time. Because the difference # between both the strings could be at max 1. while (j >= 0): sum = 0 sum += (a[j] - '0') + carry ans += (sum % 10).toString() carry = sum // 10 j -= 1 # if string a is over and string b is left while (k >= 0): sum = 0 sum += ord(b[k]) - ord('0') + carry ans += str(sum % 10) carry = (sum // 10) k -= 1 # if carry is left if (carry): ans += str(carry) # to remove leading zeroes as they will be ahead of our sum while (len(ans) and ans[len(ans) - 1] == '0'): ans.pop() # reverse our final string because we were storing sum from left to right ans = ans[::-1] return ans # Driver Codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print("Sum is " + solve(arr, n)) # This code is contributed by shinjanpatra <script> function solve(arr, n){ // sorting of array O(nlogn) arr.sort(); // Two String for storing our two minimum numbers let a = "", b = ""; // string string alternatively for (let i = 0; i < n; i += 2) { a += arr[i]; } for (let i = 1; i < n; i += 2) { b += arr[i]; } let j = a.length - 1; let k = b.length - 1; // as initial carry is zero let carry = 0; let ans = ""; while (j >= 0 && k >= 0) { let sum = 0; sum += (a.charCodeAt(j) - '0'.charCodeAt(0)) + (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); j--; k--; } // if string b is over and string a is left // here we dont need to put here while condition // as it would run at max one time. Because the difference // between both the strings could be at max 1. while (j >= 0) { let sum = 0; sum += (a[j] - '0') + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); j--; } // if string a is over and string b is left while (k >= 0) { let sum = 0; sum += (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); k--; } // if carry is left if (carry) { ans += carry.toString(); } // to remove leading zeroes as they will be ahead of our sum while (ans.length && ans[ans.length-1] == '0') ans.pop(); // reverse our final string because we were storing sum from left to right ans = ans.split('').reverse().join(''); return ans;} // Driver Code Starts. let arr = [6, 8, 4, 5, 2, 3];let n = arr.length;document.write("Sum is " + solve(arr, n)); // This code is contributed by shinjanpatra</script> Sum is 604 This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 nitin mittal souravghosh0416 aroraritesh95 shinjanpatra number-digits Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Mar, 2022" }, { "code": null, "e": 258, "s": 52, "text": "Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers. Examples : " }, { "code": null, "e": 431, "s": 258, "text": "Input: [6, 8, 4, 5, 2, 3]\nOutput: 604\nThe minimum sum is formed by numbers \n358 and 246\n\nInput: [5, 3, 0, 7, 4]\nOutput: 82\nThe minimum sum is formed by numbers \n35 and 047 " }, { "code": null, "e": 981, "s": 433, "text": "A minimum number will be formed from set of digits when smallest digit appears at most significant position and next smallest digit appears at next most significant position ans so on..The idea is to sort the array in increasing order and build two numbers by alternating picking digits from the array. So first number is formed by digits present in odd positions in the array and second number is formed by digits from even positions in the array. Finally, we return the sum of first and second number.Below is the implementation of above idea. " }, { "code": null, "e": 985, "s": 981, "text": "C++" }, { "code": null, "e": 990, "s": 985, "text": "Java" }, { "code": null, "e": 998, "s": 990, "text": "Python3" }, { "code": null, "e": 1001, "s": 998, "text": "C#" }, { "code": null, "e": 1005, "s": 1001, "text": "PHP" }, { "code": null, "e": 1016, "s": 1005, "text": "Javascript" }, { "code": "// C++ program to find minimum sum of two numbers// formed from digits of the array.#include <bits/stdc++.h>using namespace std; // Function to find and return minimum sum of// two numbers formed from digits of the array.int solve(int arr[], int n){ // sort the array sort(arr, arr + n); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate digit // of input array if (i & 1) a = a*10 + arr[i]; else b = b*10 + arr[i]; } // return the sum return a + b;} // Driver codeint main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Sum is \" << solve(arr, n); return 0;}", "e": 1764, "s": 1016, "text": null }, { "code": "// Java program to find minimum sum of two numbers// formed from digits of the array.import java.util.Arrays; class GFG { // Function to find and return minimum sum of // two numbers formed from digits of the array. static int solve(int arr[], int n) { // sort the array Arrays.sort(arr); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate // digit of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } //driver code public static void main (String[] args) { int arr[] = {6, 8, 4, 5, 2, 3}; int n = arr.length; System.out.print(\"Sum is \" + solve(arr, n)); }} //This code is contributed by Anant Agarwal.", "e": 2753, "s": 1764, "text": null }, { "code": "# Python3 program to find minimum sum of two# numbers formed from digits of the array. # Function to find and return minimum sum of# two numbers formed from digits of the array.def solve(arr, n): # sort the array arr.sort() # let two numbers be a and b a = 0; b = 0 for i in range(n): # Fill a and b with every alternate # digit of input array if (i % 2 != 0): a = a * 10 + arr[i] else: b = b * 10 + arr[i] # return the sum return a + b # Driver codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print(\"Sum is \", solve(arr, n)) # This code is contributed by Anant Agarwal.", "e": 3395, "s": 2753, "text": null }, { "code": "// C# program to find minimum// sum of two numbers formed// from digits of the array.using System; class GFG{ // Function to find and return // minimum sum of two numbers // formed from digits of the array. static int solve(int []arr, int n) { // sort the array Array.Sort(arr); // let two numbers be a and b int a = 0, b = 0; for (int i = 0; i < n; i++) { // fill a and b with every alternate digit // of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } // Driver code public static void Main () { int []arr = {6, 8, 4, 5, 2, 3}; int n = arr.Length; Console.WriteLine(\"Sum is \" + solve(arr, n)); }} // This code is contributed by Anant Agarwal.", "e": 4308, "s": 3395, "text": null }, { "code": "<?php// PHP program to find minimum// sum of two numbers formed// from digits of the array. // Function to find and return// minimum sum of two numbers// formed from digits of the array.function solve($arr, $n){ // sort the array sort($arr); sort($arr , $n); // let two numbers be a and b $a = 0; $b = 0; for ($i = 0; $i < $n; $i++) { // fill a and b with every // alternate digit of input array if ($i & 1) $a = $a * 10 + $arr[$i]; else $b = $b * 10 + $arr[$i]; } // return the sum return $a + $b;} // Driver code$arr = array(6, 8, 4, 5, 2, 3);$n = sizeof($arr);echo \"Sum is \" , solve($arr, $n); // This code is contributed by nitin mittal.?>", "e": 5035, "s": 4308, "text": null }, { "code": "<script> // Javascript program to find minimum sum of two numbers// formed from digits of the array. // Function to find and return minimum sum of // two numbers formed from digits of the array. function solve(arr, n) { // sort the array arr.sort(); // let two numbers be a and b let a = 0, b = 0; for (let i = 0; i < n; i++) { // fill a and b with every alternate // digit of input array if (i % 2 != 0) a = a * 10 + arr[i]; else b = b * 10 + arr[i]; } // return the sum return a + b; } // Driver Code let arr = [6, 8, 4, 5, 2, 3]; let n = arr.length; document.write(\"Sum is \" + solve(arr, n)); </script>", "e": 5892, "s": 5035, "text": null }, { "code": null, "e": 5902, "s": 5892, "text": "Output : " }, { "code": null, "e": 5913, "s": 5902, "text": "Sum is 604" }, { "code": null, "e": 5943, "s": 5913, "text": "Method 2 (For Large Numbers) " }, { "code": null, "e": 6196, "s": 5943, "text": "When we have to deal with very big numbers (as in the PRACTICE section of this question) the above approach will not work. The basic idea of approaching the question is the same as above, but instead of using numbers, we will use strings to handle sum." }, { "code": null, "e": 6267, "s": 6196, "text": "To add two numbers given in form of the string, you can refer to this." }, { "code": null, "e": 6271, "s": 6267, "text": "C++" }, { "code": null, "e": 6279, "s": 6271, "text": "Python3" }, { "code": null, "e": 6290, "s": 6279, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; string solve(int arr[], int n){ // code here // sorting of array O(nlogn) sort(arr, arr + n); // Two String for storing our two minimum numbers string a = \"\", b = \"\"; // string string alternatively for (int i = 0; i < n; i += 2) { a += (arr[i] + '0'); } for (int i = 1; i < n; i += 2) { b += (arr[i] + '0'); } int j = a.length() - 1; int k = b.length() - 1; // as initial carry is zero int carry = 0; string ans = \"\"; while (j >= 0 && k >= 0) { int sum = 0; sum += (a[j] - '0') + (b[k] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; j--; k--; } // if string b is over and string a is left // here we dont need to put here while condition // as it would run at max one time. Because the difference // between both the strings could be at max 1. while (j >= 0) { int sum = 0; sum += (a[j] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; j--; } // if string a is over and string b is left while (k >= 0) { int sum = 0; sum += (b[k] - '0') + carry; ans += to_string(sum % 10); carry = sum / 10; k--; } // if carry is left if (carry) { ans += to_string(carry); } // to remove leading zeroes as they will be ahead of our sum while (!ans.empty() and ans.back() == '0') ans.pop_back(); // reverse our final string because we were storing sum from left to right reverse(ans.begin(), ans.end()); return ans;} // Driver Code Starts.int main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Sum is \" << solve(arr, n); return 0;} // Driver Code Ends", "e": 8108, "s": 6290, "text": null }, { "code": "# Python code for the approachdef solve(arr, n): # sorting of array O(nlogn) arr.sort() # Two String for storing our two minimum numbers a,b = \"\",\"\" # string string alternatively for i in range(0,n,2): a += str(arr[i]) for i in range(1,n,2): b += str(arr[i]) j = len(a) - 1 k = len(b) - 1 # as initial carry is zero carry = 0 ans = \"\" while (j >= 0 and k >= 0): sum = 0 sum += (ord(a[j]) - ord('0') + ord(b[k]) - ord('0')) + carry ans += str(sum % 10) carry = sum // 10 j -= 1 k -= 1 # if string b is over and string a is left # here we dont need to put here while condition # as it would run at max one time. Because the difference # between both the strings could be at max 1. while (j >= 0): sum = 0 sum += (a[j] - '0') + carry ans += (sum % 10).toString() carry = sum // 10 j -= 1 # if string a is over and string b is left while (k >= 0): sum = 0 sum += ord(b[k]) - ord('0') + carry ans += str(sum % 10) carry = (sum // 10) k -= 1 # if carry is left if (carry): ans += str(carry) # to remove leading zeroes as they will be ahead of our sum while (len(ans) and ans[len(ans) - 1] == '0'): ans.pop() # reverse our final string because we were storing sum from left to right ans = ans[::-1] return ans # Driver Codearr = [6, 8, 4, 5, 2, 3]n = len(arr)print(\"Sum is \" + solve(arr, n)) # This code is contributed by shinjanpatra", "e": 9704, "s": 8108, "text": null }, { "code": "<script> function solve(arr, n){ // sorting of array O(nlogn) arr.sort(); // Two String for storing our two minimum numbers let a = \"\", b = \"\"; // string string alternatively for (let i = 0; i < n; i += 2) { a += arr[i]; } for (let i = 1; i < n; i += 2) { b += arr[i]; } let j = a.length - 1; let k = b.length - 1; // as initial carry is zero let carry = 0; let ans = \"\"; while (j >= 0 && k >= 0) { let sum = 0; sum += (a.charCodeAt(j) - '0'.charCodeAt(0)) + (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); j--; k--; } // if string b is over and string a is left // here we dont need to put here while condition // as it would run at max one time. Because the difference // between both the strings could be at max 1. while (j >= 0) { let sum = 0; sum += (a[j] - '0') + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); j--; } // if string a is over and string b is left while (k >= 0) { let sum = 0; sum += (b.charCodeAt(k) - '0'.charCodeAt(0)) + carry; ans += (sum % 10).toString(); carry = Math.floor(sum / 10); k--; } // if carry is left if (carry) { ans += carry.toString(); } // to remove leading zeroes as they will be ahead of our sum while (ans.length && ans[ans.length-1] == '0') ans.pop(); // reverse our final string because we were storing sum from left to right ans = ans.split('').reverse().join(''); return ans;} // Driver Code Starts. let arr = [6, 8, 4, 5, 2, 3];let n = arr.length;document.write(\"Sum is \" + solve(arr, n)); // This code is contributed by shinjanpatra</script>", "e": 11559, "s": 9704, "text": null }, { "code": null, "e": 11570, "s": 11559, "text": "Sum is 604" }, { "code": null, "e": 11959, "s": 11570, "text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 11972, "s": 11959, "text": "nitin mittal" }, { "code": null, "e": 11988, "s": 11972, "text": "souravghosh0416" }, { "code": null, "e": 12002, "s": 11988, "text": "aroraritesh95" }, { "code": null, "e": 12015, "s": 12002, "text": "shinjanpatra" }, { "code": null, "e": 12029, "s": 12015, "text": "number-digits" }, { "code": null, "e": 12036, "s": 12029, "text": "Arrays" }, { "code": null, "e": 12044, "s": 12036, "text": "Sorting" }, { "code": null, "e": 12051, "s": 12044, "text": "Arrays" }, { "code": null, "e": 12059, "s": 12051, "text": "Sorting" } ]
Visualizing the Bivariate Gaussian Distribution in Python
10 Aug, 2021 The Gaussian distribution(or normal distribution) is one of the most fundamental probability distributions in nature. From its occurrence in daily life to its applications in statistical learning techniques, it is one of the most profound mathematical discoveries ever made. This article will ahead towards the multi-dimensional distribution and get an intuitive understanding of the bivariate normal distribution. The benefit of covering the bivariate distribution is that we can visually see and understand using appropriate geometric plots. Moreover, the same concepts learned through the bivariate distribution can be extended to any number of dimensions. We’ll first briefly cover the theoretical aspects of the distribution and do an exhaustive analysis of the various aspects of it, like the covariance matrix and the density function in Python! The density function describes the relative likelihood of a random variable at a given sample. If the value is high around a given sample, that means that the random variable will most probably take on that value when sampled at random. Responsible for its characteristic “bell shape”, the density function of a given bivariate Gaussian random variable is mathematically defined as: Whereis any input vector while the symbols and have their usual meaning. The main function used in this article is the scipy.stats.multivariate_normal function from the Scipy utility for a multivariate normal random variable. Syntax: scipy.stats.multivariate_normal(mean=None, cov=1) Non-optional Parameters: mean: A Numpy array specifyinh the mean of the distribution cov: A Numpy array specifying a positive definite covariance matrix seed: A random seed for generating reproducible results Returns: A multivariate normal random variable object scipy.stats._multivariate.multivariate_normal_gen object. Some of the methods of the returned object which are useful for this article are as follows: pdf(x): Returns the density function value at the value ‘x’ rvs(size): Draws ‘size’ number of samples from the generated multivariate Gaussian distribution The covariance matrix is perhaps one of the most resourceful components of a bivariate Gaussian distribution. Each element of the covariance matrix defines the covariance between each subsequent pair of random variables. The covariance between two random variables and is mathematically defined as where denotes the expected value of a given random variable . Intuitively speaking, by observing the diagonal elements of the covariance matrix we can easily imagine the contour drawn out by the two Gaussian random variables in 2D. Here’s how: The values present in the right diagonal represent the joint covariance between two components of the corresponding random variables. If the value is +ve, that means there is positive covariance between the two random variables which means that if we go in a direction where increases then will increase in that direction also and vice versa. Similarly, if the value is negative that means will decrease in the direction of an increase in . Below is the implementation of the covariance matrix: In the following code snippets we’ll be generating 3 different Gaussian bivariate distributions with same mean but different covariance matrices: Covariance matrix with -ve covariance = Covariance matrix with 0 covariance = Covariance matrix with +ve covariance = Covariance matrix with -ve covariance = Covariance matrix with 0 covariance = Covariance matrix with +ve covariance = Python # Importing the necessary modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import multivariate_normal plt.style.use('seaborn-dark')plt.rcParams['figure.figsize']=14,6 # Initializing the random seedrandom_seed=1000 # List containing the variance# covariance valuescov_val = [-0.8, 0, 0.8] # Setting mean of the distributino to# be at (0,0)mean = np.array([0,0]) # Iterating over different covariance# valuesfor idx, val in enumerate(cov_val): plt.subplot(1,3,idx+1) # Initializing the covariance matrix cov = np.array([[1, val], [val, 1]]) # Generating a Gaussian bivariate distribution # with given mean and covariance matrix distr = multivariate_normal(cov = cov, mean = mean, seed = random_seed) # Generating 5000 samples out of the # distribution data = distr.rvs(size = 5000) # Plotting the generated samples plt.plot(data[:,0],data[:,1], 'o', c='lime', markeredgewidth = 0.5, markeredgecolor = 'black') plt.title(f'Covariance between x1 and x2 = {val}') plt.xlabel('x1') plt.ylabel('x2') plt.axis('equal') plt.show() Output: Samples generated for different covariance matrices We can see that the code’s output has successfully met our theoretical proofs! Note that the value 0.8 was taken just for convenience purposes. The reader can play around with different magnitudes of covariance and expect consistent results. Now we can move over to one of the most interesting and characteristic aspects of the bivariate Gaussian distribution, the density function! The density function is responsible for the characteristic bell shape of the distribution. Python # Importing the necessary modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import multivariate_normal plt.style.use('seaborn-dark')plt.rcParams['figure.figsize']=14,6fig = plt.figure() # Initializing the random seedrandom_seed=1000 # List containing the variance# covariance valuescov_val = [-0.8, 0, 0.8] # Setting mean of the distributino# to be at (0,0)mean = np.array([0,0]) # Storing density function values for# further analysispdf_list = [] # Iterating over different covariance valuesfor idx, val in enumerate(cov_val): # Initializing the covariance matrix cov = np.array([[1, val], [val, 1]]) # Generating a Gaussian bivariate distribution # with given mean and covariance matrix distr = multivariate_normal(cov = cov, mean = mean, seed = random_seed) # Generating a meshgrid complacent with # the 3-sigma boundary mean_1, mean_2 = mean[0], mean[1] sigma_1, sigma_2 = cov[0,0], cov[1,1] x = np.linspace(-3*sigma_1, 3*sigma_1, num=100) y = np.linspace(-3*sigma_2, 3*sigma_2, num=100) X, Y = np.meshgrid(x,y) # Generating the density function # for each point in the meshgrid pdf = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): pdf[i,j] = distr.pdf([X[i,j], Y[i,j]]) # Plotting the density function values key = 131+idx ax = fig.add_subplot(key, projection = '3d') ax.plot_surface(X, Y, pdf, cmap = 'viridis') plt.xlabel("x1") plt.ylabel("x2") plt.title(f'Covariance between x1 and x2 = {val}') pdf_list.append(pdf) ax.axes.zaxis.set_ticks([]) plt.tight_layout()plt.show() # Plotting contour plotsfor idx, val in enumerate(pdf_list): plt.subplot(1,3,idx+1) plt.contourf(X, Y, val, cmap='viridis') plt.xlabel("x1") plt.ylabel("x2") plt.title(f'Covariance between x1 and x2 = {cov_val[idx]}')plt.tight_layout()plt.show() Output: 1) Plot of the density function Density functions corresponding to different covariance matrices 2) Plot of contours Contours of the density functions As we can see, the density function’s contours exactly match the samples drawn by us in the previous section. Note that the 3 sigma boundary(concluded from the 68-95-99.7 rule) ensures maximum sample coverage for the defined distribution. As mentioned earlier, the reader can play around with different boundaries and expect consistent results. We understood the various intricacies behind the Gaussian bivariate distribution through a series of plots and verified the theoretical results with the practical findings using Python. The reader is encouraged to play around with the code snippets for gaining a much more profound intuition about this magical distribution! adityasaini70 Data Visualization Picked Python-matplotlib Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Aug, 2021" }, { "code": null, "e": 469, "s": 54, "text": "The Gaussian distribution(or normal distribution) is one of the most fundamental probability distributions in nature. From its occurrence in daily life to its applications in statistical learning techniques, it is one of the most profound mathematical discoveries ever made. This article will ahead towards the multi-dimensional distribution and get an intuitive understanding of the bivariate normal distribution." }, { "code": null, "e": 907, "s": 469, "text": "The benefit of covering the bivariate distribution is that we can visually see and understand using appropriate geometric plots. Moreover, the same concepts learned through the bivariate distribution can be extended to any number of dimensions. We’ll first briefly cover the theoretical aspects of the distribution and do an exhaustive analysis of the various aspects of it, like the covariance matrix and the density function in Python!" }, { "code": null, "e": 1292, "s": 907, "text": "The density function describes the relative likelihood of a random variable at a given sample. If the value is high around a given sample, that means that the random variable will most probably take on that value when sampled at random. Responsible for its characteristic “bell shape”, the density function of a given bivariate Gaussian random variable is mathematically defined as:" }, { "code": null, "e": 1367, "s": 1292, "text": "Whereis any input vector while the symbols and have their usual meaning." }, { "code": null, "e": 1520, "s": 1367, "text": "The main function used in this article is the scipy.stats.multivariate_normal function from the Scipy utility for a multivariate normal random variable." }, { "code": null, "e": 1578, "s": 1520, "text": "Syntax: scipy.stats.multivariate_normal(mean=None, cov=1)" }, { "code": null, "e": 1603, "s": 1578, "text": "Non-optional Parameters:" }, { "code": null, "e": 1663, "s": 1603, "text": "mean: A Numpy array specifyinh the mean of the distribution" }, { "code": null, "e": 1731, "s": 1663, "text": "cov: A Numpy array specifying a positive definite covariance matrix" }, { "code": null, "e": 1787, "s": 1731, "text": "seed: A random seed for generating reproducible results" }, { "code": null, "e": 1992, "s": 1787, "text": "Returns: A multivariate normal random variable object scipy.stats._multivariate.multivariate_normal_gen object. Some of the methods of the returned object which are useful for this article are as follows:" }, { "code": null, "e": 2052, "s": 1992, "text": "pdf(x): Returns the density function value at the value ‘x’" }, { "code": null, "e": 2148, "s": 2052, "text": "rvs(size): Draws ‘size’ number of samples from the generated multivariate Gaussian distribution" }, { "code": null, "e": 2695, "s": 2148, "text": "The covariance matrix is perhaps one of the most resourceful components of a bivariate Gaussian distribution. Each element of the covariance matrix defines the covariance between each subsequent pair of random variables. The covariance between two random variables and is mathematically defined as where denotes the expected value of a given random variable . Intuitively speaking, by observing the diagonal elements of the covariance matrix we can easily imagine the contour drawn out by the two Gaussian random variables in 2D. Here’s how:" }, { "code": null, "e": 3139, "s": 2695, "text": "The values present in the right diagonal represent the joint covariance between two components of the corresponding random variables. If the value is +ve, that means there is positive covariance between the two random variables which means that if we go in a direction where increases then will increase in that direction also and vice versa. Similarly, if the value is negative that means will decrease in the direction of an increase in ." }, { "code": null, "e": 3193, "s": 3139, "text": "Below is the implementation of the covariance matrix:" }, { "code": null, "e": 3340, "s": 3193, "text": "In the following code snippets we’ll be generating 3 different Gaussian bivariate distributions with same mean but different covariance matrices: " }, { "code": null, "e": 3459, "s": 3340, "text": "Covariance matrix with -ve covariance = Covariance matrix with 0 covariance = Covariance matrix with +ve covariance = " }, { "code": null, "e": 3500, "s": 3459, "text": "Covariance matrix with -ve covariance = " }, { "code": null, "e": 3539, "s": 3500, "text": "Covariance matrix with 0 covariance = " }, { "code": null, "e": 3580, "s": 3539, "text": "Covariance matrix with +ve covariance = " }, { "code": null, "e": 3587, "s": 3580, "text": "Python" }, { "code": "# Importing the necessary modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import multivariate_normal plt.style.use('seaborn-dark')plt.rcParams['figure.figsize']=14,6 # Initializing the random seedrandom_seed=1000 # List containing the variance# covariance valuescov_val = [-0.8, 0, 0.8] # Setting mean of the distributino to# be at (0,0)mean = np.array([0,0]) # Iterating over different covariance# valuesfor idx, val in enumerate(cov_val): plt.subplot(1,3,idx+1) # Initializing the covariance matrix cov = np.array([[1, val], [val, 1]]) # Generating a Gaussian bivariate distribution # with given mean and covariance matrix distr = multivariate_normal(cov = cov, mean = mean, seed = random_seed) # Generating 5000 samples out of the # distribution data = distr.rvs(size = 5000) # Plotting the generated samples plt.plot(data[:,0],data[:,1], 'o', c='lime', markeredgewidth = 0.5, markeredgecolor = 'black') plt.title(f'Covariance between x1 and x2 = {val}') plt.xlabel('x1') plt.ylabel('x2') plt.axis('equal') plt.show()", "e": 4758, "s": 3587, "text": null }, { "code": null, "e": 4766, "s": 4758, "text": "Output:" }, { "code": null, "e": 4818, "s": 4766, "text": "Samples generated for different covariance matrices" }, { "code": null, "e": 5060, "s": 4818, "text": "We can see that the code’s output has successfully met our theoretical proofs! Note that the value 0.8 was taken just for convenience purposes. The reader can play around with different magnitudes of covariance and expect consistent results." }, { "code": null, "e": 5292, "s": 5060, "text": "Now we can move over to one of the most interesting and characteristic aspects of the bivariate Gaussian distribution, the density function! The density function is responsible for the characteristic bell shape of the distribution." }, { "code": null, "e": 5299, "s": 5292, "text": "Python" }, { "code": "# Importing the necessary modulesimport numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import multivariate_normal plt.style.use('seaborn-dark')plt.rcParams['figure.figsize']=14,6fig = plt.figure() # Initializing the random seedrandom_seed=1000 # List containing the variance# covariance valuescov_val = [-0.8, 0, 0.8] # Setting mean of the distributino# to be at (0,0)mean = np.array([0,0]) # Storing density function values for# further analysispdf_list = [] # Iterating over different covariance valuesfor idx, val in enumerate(cov_val): # Initializing the covariance matrix cov = np.array([[1, val], [val, 1]]) # Generating a Gaussian bivariate distribution # with given mean and covariance matrix distr = multivariate_normal(cov = cov, mean = mean, seed = random_seed) # Generating a meshgrid complacent with # the 3-sigma boundary mean_1, mean_2 = mean[0], mean[1] sigma_1, sigma_2 = cov[0,0], cov[1,1] x = np.linspace(-3*sigma_1, 3*sigma_1, num=100) y = np.linspace(-3*sigma_2, 3*sigma_2, num=100) X, Y = np.meshgrid(x,y) # Generating the density function # for each point in the meshgrid pdf = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): pdf[i,j] = distr.pdf([X[i,j], Y[i,j]]) # Plotting the density function values key = 131+idx ax = fig.add_subplot(key, projection = '3d') ax.plot_surface(X, Y, pdf, cmap = 'viridis') plt.xlabel(\"x1\") plt.ylabel(\"x2\") plt.title(f'Covariance between x1 and x2 = {val}') pdf_list.append(pdf) ax.axes.zaxis.set_ticks([]) plt.tight_layout()plt.show() # Plotting contour plotsfor idx, val in enumerate(pdf_list): plt.subplot(1,3,idx+1) plt.contourf(X, Y, val, cmap='viridis') plt.xlabel(\"x1\") plt.ylabel(\"x2\") plt.title(f'Covariance between x1 and x2 = {cov_val[idx]}')plt.tight_layout()plt.show()", "e": 7247, "s": 5299, "text": null }, { "code": null, "e": 7255, "s": 7247, "text": "Output:" }, { "code": null, "e": 7287, "s": 7255, "text": "1) Plot of the density function" }, { "code": null, "e": 7352, "s": 7287, "text": "Density functions corresponding to different covariance matrices" }, { "code": null, "e": 7372, "s": 7352, "text": "2) Plot of contours" }, { "code": null, "e": 7406, "s": 7372, "text": "Contours of the density functions" }, { "code": null, "e": 7751, "s": 7406, "text": "As we can see, the density function’s contours exactly match the samples drawn by us in the previous section. Note that the 3 sigma boundary(concluded from the 68-95-99.7 rule) ensures maximum sample coverage for the defined distribution. As mentioned earlier, the reader can play around with different boundaries and expect consistent results." }, { "code": null, "e": 8076, "s": 7751, "text": "We understood the various intricacies behind the Gaussian bivariate distribution through a series of plots and verified the theoretical results with the practical findings using Python. The reader is encouraged to play around with the code snippets for gaining a much more profound intuition about this magical distribution!" }, { "code": null, "e": 8090, "s": 8076, "text": "adityasaini70" }, { "code": null, "e": 8109, "s": 8090, "text": "Data Visualization" }, { "code": null, "e": 8116, "s": 8109, "text": "Picked" }, { "code": null, "e": 8134, "s": 8116, "text": "Python-matplotlib" }, { "code": null, "e": 8147, "s": 8134, "text": "Python-scipy" }, { "code": null, "e": 8154, "s": 8147, "text": "Python" } ]
C/C++ Ternary Operator – Some Interesting Observations
31 Jul, 2018 Predict the output of following C++ program. #include <iostream>using namespace std; int main(){ int test = 0; cout << "First character " << '1' << endl; cout << "Second character " << (test ? 3 : '1') << endl; return 0;} One would expect the output will be same in both the print statements. However, the output will be, First character 1Second character 49 Why the second statement printing 49? Read on the ternary expression. Ternary Operator (C/C++): A ternary operator has the following form, exp1 ? exp2 : exp3 The expression exp1 will be evaluated always. Execution of exp2 and exp3 depends on the outcome of exp1. If the outcome of exp1 is non zero exp2 will be evaluated, otherwise exp3 will be evaluated. Side Effects: Any side effects of exp1 will be evaluated and updated immediately before executing exp2 or exp3. In other words, there is sequence point after the evaluation of condition in the ternary expression. If either exp2 or exp3 have side effects, only one of them will be evaluated. Return Type: It is another interesting fact. The ternary operator has return type. The return type depends on exp2, and convertibility of exp3 into exp2 as per usual\overloaded conversion rules. If they are not convertible, the compiler throws an error. See the examples below, The following program compiles without any error. The return type of ternary expression is expected to be float (as that of exp2) and exp3 (i.e. literal zero – int type) is implicitly convertible to float. #include <iostream>using namespace std; int main(){ int test = 0; float fvalue = 3.111f; cout << (test ? fvalue : 0) << endl; return 0;} The following program will not compile, because the compiler is unable to find return type of ternary expression or implicit conversion is unavailable between exp2 (char array) and exp3 (int). #include <iostream>using namespace std; int main(){ int test = 0; cout << test ? "A String" : 0 << endl; return 0;} The following program *may* compile, or but fails at runtime. The return type of ternary expression is bounded to type (char *), yet the expression returns int, hence the program fails. Literally, the program tries to print string at 0th address at runtime. #include <iostream>using namespace std; int main(){ int test = 0; cout << (test ? "A String" : 0) << endl; return 0;} We can observe that exp2 is considered as output type and exp3 will be converted into exp2 at runtime. If the conversion is implicit the compiler inserts stubs for conversion. If the conversion is explicit the compiler throws an error. If any compiler misses to catch such error, the program may fail at runtime. Best Practice: It is the power of C++ type system that avoids such bugs. Make sure both the expressions exp2 and exp3 return same type or atleast safely convertible types. We can see other idioms like C++ convert union for safe conversion. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. We will be happy to learn and update from other geeks. C-Operators C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Jul, 2018" }, { "code": null, "e": 97, "s": 52, "text": "Predict the output of following C++ program." }, { "code": "#include <iostream>using namespace std; int main(){ int test = 0; cout << \"First character \" << '1' << endl; cout << \"Second character \" << (test ? 3 : '1') << endl; return 0;}", "e": 286, "s": 97, "text": null }, { "code": null, "e": 386, "s": 286, "text": "One would expect the output will be same in both the print statements. However, the output will be," }, { "code": "First character 1Second character 49", "e": 424, "s": 386, "text": null }, { "code": null, "e": 494, "s": 424, "text": "Why the second statement printing 49? Read on the ternary expression." }, { "code": null, "e": 520, "s": 494, "text": "Ternary Operator (C/C++):" }, { "code": null, "e": 563, "s": 520, "text": "A ternary operator has the following form," }, { "code": null, "e": 582, "s": 563, "text": "exp1 ? exp2 : exp3" }, { "code": null, "e": 780, "s": 582, "text": "The expression exp1 will be evaluated always. Execution of exp2 and exp3 depends on the outcome of exp1. If the outcome of exp1 is non zero exp2 will be evaluated, otherwise exp3 will be evaluated." }, { "code": null, "e": 794, "s": 780, "text": "Side Effects:" }, { "code": null, "e": 1071, "s": 794, "text": "Any side effects of exp1 will be evaluated and updated immediately before executing exp2 or exp3. In other words, there is sequence point after the evaluation of condition in the ternary expression. If either exp2 or exp3 have side effects, only one of them will be evaluated." }, { "code": null, "e": 1084, "s": 1071, "text": "Return Type:" }, { "code": null, "e": 1349, "s": 1084, "text": "It is another interesting fact. The ternary operator has return type. The return type depends on exp2, and convertibility of exp3 into exp2 as per usual\\overloaded conversion rules. If they are not convertible, the compiler throws an error. See the examples below," }, { "code": null, "e": 1555, "s": 1349, "text": "The following program compiles without any error. The return type of ternary expression is expected to be float (as that of exp2) and exp3 (i.e. literal zero – int type) is implicitly convertible to float." }, { "code": "#include <iostream>using namespace std; int main(){ int test = 0; float fvalue = 3.111f; cout << (test ? fvalue : 0) << endl; return 0;}", "e": 1703, "s": 1555, "text": null }, { "code": null, "e": 1896, "s": 1703, "text": "The following program will not compile, because the compiler is unable to find return type of ternary expression or implicit conversion is unavailable between exp2 (char array) and exp3 (int)." }, { "code": "#include <iostream>using namespace std; int main(){ int test = 0; cout << test ? \"A String\" : 0 << endl; return 0;}", "e": 2021, "s": 1896, "text": null }, { "code": null, "e": 2279, "s": 2021, "text": "The following program *may* compile, or but fails at runtime. The return type of ternary expression is bounded to type (char *), yet the expression returns int, hence the program fails. Literally, the program tries to print string at 0th address at runtime." }, { "code": "#include <iostream>using namespace std; int main(){ int test = 0; cout << (test ? \"A String\" : 0) << endl; return 0;}", "e": 2406, "s": 2279, "text": null }, { "code": null, "e": 2719, "s": 2406, "text": "We can observe that exp2 is considered as output type and exp3 will be converted into exp2 at runtime. If the conversion is implicit the compiler inserts stubs for conversion. If the conversion is explicit the compiler throws an error. If any compiler misses to catch such error, the program may fail at runtime." }, { "code": null, "e": 2734, "s": 2719, "text": "Best Practice:" }, { "code": null, "e": 2959, "s": 2734, "text": "It is the power of C++ type system that avoids such bugs. Make sure both the expressions exp2 and exp3 return same type or atleast safely convertible types. We can see other idioms like C++ convert union for safe conversion." }, { "code": null, "e": 3139, "s": 2959, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. We will be happy to learn and update from other geeks." }, { "code": null, "e": 3151, "s": 3139, "text": "C-Operators" }, { "code": null, "e": 3162, "s": 3151, "text": "C Language" }, { "code": null, "e": 3166, "s": 3162, "text": "C++" }, { "code": null, "e": 3170, "s": 3166, "text": "CPP" } ]
File Updation in Software Engineering
14 Nov, 2019 Prerequisite – File OrganisationData is not static as it is constantly changing and these changes need to be reflected in their files. The function that keeps files current is known as updating. Update Files:Three specific files are associated while updating a file. The permanent data file, called the master file contains the most current file data.The transaction file contains changes to be applied to the master file.The third file needed in an update program is an error report file. The error report contains a listing of all errors discovered during the update process and is presented to the user for corrective action. The permanent data file, called the master file contains the most current file data. The transaction file contains changes to be applied to the master file. The third file needed in an update program is an error report file. The error report contains a listing of all errors discovered during the update process and is presented to the user for corrective action. Three basic types of changes occur in all file updates: Adding new data, deleting old data, modify data containing revisions.To process any of these transactions, we need a key. A key is one or more fields that uniquely identify the data in the file. For example, in a student file, the key would be student ID. In an employee file, the key would be Social Security number. File updates are of 2 types: In a batch update, changes are collected over time and then all changes are applied to the file at once. In an online update, the user is directly connected to the computer and the changes are processed one at a time-often as the change occurs. Sequential File Update:Assuming a batch, sequential file environment. It is a file that must be processed serially starting at the beginning without any random processing capabilities. A sequential file update actually has two copies of the master file, the old master and the new master. In the above figure, we see the four files we discussed above. Tape symbol for the files because it is the classic symbol for sequential files. After the update program completes, the new master file is sent to off-line storage, where it is kept until it is needed again. When the file is to be updated, the master file is retrieved from the off-line storage and used as the old master. Generally, at least three copies of a master file are retained in off-line storage, in case it becomes necessary to regenerate an unreadable file. This retention cycle is known as the grandparent system because three generations of the file are always available: the grandparent, the parent and the child. The Update Program Design:The update process requires that we match the keys on the transaction and master file and, assuming that there are no errors, one of the following three actions/rules are followed: If the transaction file key is less than the master file key, the transaction is added to the new master.If the transaction file key is equal to the master file key, either(a). The contents of the master file are changed if the transaction is a revise transaction, or(b). The data is removed from the master file if the transaction is a delete.If the transaction file key is greater than the master file key, the old master file record is written to the new master file. If the transaction file key is less than the master file key, the transaction is added to the new master. If the transaction file key is equal to the master file key, either(a). The contents of the master file are changed if the transaction is a revise transaction, or(b). The data is removed from the master file if the transaction is a delete. (a). The contents of the master file are changed if the transaction is a revise transaction, or (b). The data is removed from the master file if the transaction is a delete. If the transaction file key is greater than the master file key, the old master file record is written to the new master file. This updating process is shown in Figure above. In the transaction file, the transaction codes are A for add, D for delete, and R for revise. The process begins by matching the keys for the first record on each file, in this case, 14 > 10 Thus, Rule 3 is used, and the master record is written to the new master record. Then 14 and 13 are matched, which results in 13 being written to the new master. In the next match, we have 14 == 14 Thus, according to Rule 2a, the data is used in the transaction file to change the data in the master file. However, the new master file is not written at this time. More transactions may match the master file, and they too need to be processed. After writing 16 to the new master, the situation is 17 < 20 According to Rule 1, 17 must be added to the new master file. To do transactions are copied to the new master file, but not written yet.The processing continues until the delete transaction is read, at which the following situation occurs 21 == 21 and since the transaction is a delete, according to Rule 2b, 21 is dropped from the new master file. To do this, the next master record and transaction record is read without writing the new master. The processing continues in a similar fashion until all records on both files have been processed. Update Errors:Two general classes of errors can occur in an update program. The first being bad data implying that attributes which are not a part of the data. The second class of errors is file errors. File errors occur when the data on the transaction file are not in synchronization with the data on the master file. 3 different situations can occur: An add transaction matches a record with the same key on the master file. Master files do not allow duplicate data to be present. When the key on an add transaction matches a key on the master file, therefore, the transaction is rejected as invalid and it is reported on the error report.A revise transaction’s key does not match a record on the master file. In this case, user is trying to change data that do not exist. This is also a file error and must be reported on the error report.A delete transaction’s key does not match a record on the master file. In this case, user is trying to delete data that do not exist, and this must also be reported as an error. An add transaction matches a record with the same key on the master file. Master files do not allow duplicate data to be present. When the key on an add transaction matches a key on the master file, therefore, the transaction is rejected as invalid and it is reported on the error report. A revise transaction’s key does not match a record on the master file. In this case, user is trying to change data that do not exist. This is also a file error and must be reported on the error report. A delete transaction’s key does not match a record on the master file. In this case, user is trying to delete data that do not exist, and this must also be reported as an error. Update Logic:Initialization is a function that opens the files and otherwise prepares the environment for processing. The mainline processing is done in Process. End of Job is a function that closes the files and displays any end of job messages. Pseudocode for File Update: 1 read first record from transaction file 2 read first record from old master file 3 select next entity to be processed 4 loop current entity not sentinel 1 if current entity equals old master entity 1 copy old master to new master work area 2 read old master file 2 end if 3 if current entity equals transaction entity 1 update new master work area 4 end if 5 if current entity equals new master entity 1 write new master file 6 end if 7 select next entity to be processed 5 end loop The first three statements contain initialization logic for Process. The driving force behind the update logic is that in each while loop, all the data is processed for one entity. To determine which entity, the next (statements and 4.7) are processed, the current entry is determined by comparing the current transaction key to the current master key. The current key is the smaller. Before comparing the keys, however the first record must be read in each file. This is known as priming the files and is seen in statements 1 and 2. The loop statement in Algorithm contains the driving logic for the entire program. It is built on a very simple principle: As long as data are present in either the transaction file or the master file, the loop continues. When a file has been completely read, its key is set to a sentinel value. When both files are at their end, therefore, both of their keys will be sentinels. Then, what is selected as the next entity to be processed, it will be a sentinel, which is the event that terminates the while loop. Three major processing functions take place in the while loop. First, it is determined if the entity on the old master file needs to be processed. If it does, it is moved to the new master output area and the next entity is read from the old master file. The key on the old master can match the current key in two situations: a change or delete transaction exists for the current entity. This logic is seen in statement 4.1. The second major process handles transactions that match the current entity. It calls a function that determines the type of transaction being processed (add, change, or delete) and handles it accordingly. If it is an add, it moves the new entity data to the new master area. If it is a change, it updates the data in the new master area. And if it is a delete, it clears the key in the new master area so that the record will not be written. To handle multiple transactions in the update function, it reads the next transaction and continues if its key matches the current entity. The last major process writes the new master when appropriate. If the current entity matches the key in the new master file area, then the record needs to be written to the file. This will be the case unless a delete transaction was processed. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Nov, 2019" }, { "code": null, "e": 223, "s": 28, "text": "Prerequisite – File OrganisationData is not static as it is constantly changing and these changes need to be reflected in their files. The function that keeps files current is known as updating." }, { "code": null, "e": 295, "s": 223, "text": "Update Files:Three specific files are associated while updating a file." }, { "code": null, "e": 657, "s": 295, "text": "The permanent data file, called the master file contains the most current file data.The transaction file contains changes to be applied to the master file.The third file needed in an update program is an error report file. The error report contains a listing of all errors discovered during the update process and is presented to the user for corrective action." }, { "code": null, "e": 742, "s": 657, "text": "The permanent data file, called the master file contains the most current file data." }, { "code": null, "e": 814, "s": 742, "text": "The transaction file contains changes to be applied to the master file." }, { "code": null, "e": 1021, "s": 814, "text": "The third file needed in an update program is an error report file. The error report contains a listing of all errors discovered during the update process and is presented to the user for corrective action." }, { "code": null, "e": 1395, "s": 1021, "text": "Three basic types of changes occur in all file updates: Adding new data, deleting old data, modify data containing revisions.To process any of these transactions, we need a key. A key is one or more fields that uniquely identify the data in the file. For example, in a student file, the key would be student ID. In an employee file, the key would be Social Security number." }, { "code": null, "e": 1424, "s": 1395, "text": "File updates are of 2 types:" }, { "code": null, "e": 1529, "s": 1424, "text": "In a batch update, changes are collected over time and then all changes are applied to the file at once." }, { "code": null, "e": 1669, "s": 1529, "text": "In an online update, the user is directly connected to the computer and the changes are processed one at a time-often as the change occurs." }, { "code": null, "e": 1958, "s": 1669, "text": "Sequential File Update:Assuming a batch, sequential file environment. It is a file that must be processed serially starting at the beginning without any random processing capabilities. A sequential file update actually has two copies of the master file, the old master and the new master." }, { "code": null, "e": 2345, "s": 1958, "text": "In the above figure, we see the four files we discussed above. Tape symbol for the files because it is the classic symbol for sequential files. After the update program completes, the new master file is sent to off-line storage, where it is kept until it is needed again. When the file is to be updated, the master file is retrieved from the off-line storage and used as the old master." }, { "code": null, "e": 2651, "s": 2345, "text": "Generally, at least three copies of a master file are retained in off-line storage, in case it becomes necessary to regenerate an unreadable file. This retention cycle is known as the grandparent system because three generations of the file are always available: the grandparent, the parent and the child." }, { "code": null, "e": 2858, "s": 2651, "text": "The Update Program Design:The update process requires that we match the keys on the transaction and master file and, assuming that there are no errors, one of the following three actions/rules are followed:" }, { "code": null, "e": 3329, "s": 2858, "text": "If the transaction file key is less than the master file key, the transaction is added to the new master.If the transaction file key is equal to the master file key, either(a). The contents of the master file are changed if the transaction is a revise transaction, or(b). The data is removed from the master file if the transaction is a delete.If the transaction file key is greater than the master file key, the old master file record is written to the new master file." }, { "code": null, "e": 3435, "s": 3329, "text": "If the transaction file key is less than the master file key, the transaction is added to the new master." }, { "code": null, "e": 3675, "s": 3435, "text": "If the transaction file key is equal to the master file key, either(a). The contents of the master file are changed if the transaction is a revise transaction, or(b). The data is removed from the master file if the transaction is a delete." }, { "code": null, "e": 3771, "s": 3675, "text": "(a). The contents of the master file are changed if the transaction is a revise transaction, or" }, { "code": null, "e": 3849, "s": 3771, "text": "(b). The data is removed from the master file if the transaction is a delete." }, { "code": null, "e": 3976, "s": 3849, "text": "If the transaction file key is greater than the master file key, the old master file record is written to the new master file." }, { "code": null, "e": 4207, "s": 3976, "text": "This updating process is shown in Figure above. In the transaction file, the transaction codes are A for add, D for delete, and R for revise. The process begins by matching the keys for the first record on each file, in this case," }, { "code": null, "e": 4215, "s": 4207, "text": "14 > 10" }, { "code": null, "e": 4404, "s": 4215, "text": "Thus, Rule 3 is used, and the master record is written to the new master record. Then 14 and 13 are matched, which results in 13 being written to the new master. In the next match, we have" }, { "code": null, "e": 4413, "s": 4404, "text": "14 == 14" }, { "code": null, "e": 4712, "s": 4413, "text": "Thus, according to Rule 2a, the data is used in the transaction file to change the data in the master file. However, the new master file is not written at this time. More transactions may match the master file, and they too need to be processed. After writing 16 to the new master, the situation is" }, { "code": null, "e": 4720, "s": 4712, "text": "17 < 20" }, { "code": null, "e": 4959, "s": 4720, "text": "According to Rule 1, 17 must be added to the new master file. To do transactions are copied to the new master file, but not written yet.The processing continues until the delete transaction is read, at which the following situation occurs" }, { "code": null, "e": 4968, "s": 4959, "text": "21 == 21" }, { "code": null, "e": 5266, "s": 4968, "text": "and since the transaction is a delete, according to Rule 2b, 21 is dropped from the new master file. To do this, the next master record and transaction record is read without writing the new master. The processing continues in a similar fashion until all records on both files have been processed." }, { "code": null, "e": 5586, "s": 5266, "text": "Update Errors:Two general classes of errors can occur in an update program. The first being bad data implying that attributes which are not a part of the data. The second class of errors is file errors. File errors occur when the data on the transaction file are not in synchronization with the data on the master file." }, { "code": null, "e": 5620, "s": 5586, "text": "3 different situations can occur:" }, { "code": null, "e": 6287, "s": 5620, "text": "An add transaction matches a record with the same key on the master file. Master files do not allow duplicate data to be present. When the key on an add transaction matches a key on the master file, therefore, the transaction is rejected as invalid and it is reported on the error report.A revise transaction’s key does not match a record on the master file. In this case, user is trying to change data that do not exist. This is also a file error and must be reported on the error report.A delete transaction’s key does not match a record on the master file. In this case, user is trying to delete data that do not exist, and this must also be reported as an error." }, { "code": null, "e": 6576, "s": 6287, "text": "An add transaction matches a record with the same key on the master file. Master files do not allow duplicate data to be present. When the key on an add transaction matches a key on the master file, therefore, the transaction is rejected as invalid and it is reported on the error report." }, { "code": null, "e": 6778, "s": 6576, "text": "A revise transaction’s key does not match a record on the master file. In this case, user is trying to change data that do not exist. This is also a file error and must be reported on the error report." }, { "code": null, "e": 6956, "s": 6778, "text": "A delete transaction’s key does not match a record on the master file. In this case, user is trying to delete data that do not exist, and this must also be reported as an error." }, { "code": null, "e": 7203, "s": 6956, "text": "Update Logic:Initialization is a function that opens the files and otherwise prepares the environment for processing. The mainline processing is done in Process. End of Job is a function that closes the files and displays any end of job messages." }, { "code": null, "e": 7231, "s": 7203, "text": "Pseudocode for File Update:" }, { "code": null, "e": 7803, "s": 7231, "text": "1 read first record from transaction file\n2 read first record from old master file\n3 select next entity to be processed\n4 loop current entity not sentinel\n 1 if current entity equals old master entity\n 1 copy old master to new master work area\n 2 read old master file\n 2 end if\n 3 if current entity equals transaction entity\n 1 update new master work area\n 4 end if\n 5 if current entity equals new master entity\n 1 write new master file\n 6 end if\n 7 select next entity to be processed\n5 end loop " }, { "code": null, "e": 8188, "s": 7803, "text": "The first three statements contain initialization logic for Process. The driving force behind the update logic is that in each while loop, all the data is processed for one entity. To determine which entity, the next (statements and 4.7) are processed, the current entry is determined by comparing the current transaction key to the current master key. The current key is the smaller." }, { "code": null, "e": 8849, "s": 8188, "text": "Before comparing the keys, however the first record must be read in each file. This is known as priming the files and is seen in statements 1 and 2. The loop statement in Algorithm contains the driving logic for the entire program. It is built on a very simple principle: As long as data are present in either the transaction file or the master file, the loop continues. When a file has been completely read, its key is set to a sentinel value. When both files are at their end, therefore, both of their keys will be sentinels. Then, what is selected as the next entity to be processed, it will be a sentinel, which is the event that terminates the while loop." }, { "code": null, "e": 8912, "s": 8849, "text": "Three major processing functions take place in the while loop." }, { "code": null, "e": 9274, "s": 8912, "text": "First, it is determined if the entity on the old master file needs to be processed. If it does, it is moved to the new master output area and the next entity is read from the old master file. The key on the old master can match the current key in two situations: a change or delete transaction exists for the current entity. This logic is seen in statement 4.1." }, { "code": null, "e": 9856, "s": 9274, "text": "The second major process handles transactions that match the current entity. It calls a function that determines the type of transaction being processed (add, change, or delete) and handles it accordingly. If it is an add, it moves the new entity data to the new master area. If it is a change, it updates the data in the new master area. And if it is a delete, it clears the key in the new master area so that the record will not be written. To handle multiple transactions in the update function, it reads the next transaction and continues if its key matches the current entity." }, { "code": null, "e": 10100, "s": 9856, "text": "The last major process writes the new master when appropriate. If the current entity matches the key in the new master file area, then the record needs to be written to the file. This will be the case unless a delete transaction was processed." }, { "code": null, "e": 10121, "s": 10100, "text": "Software Engineering" } ]
Read a specific bit of a number with Arduino
Each number has a specific binary representation. For example, 8 can be represented as 0b1000, 15 can be represented as 0b1111, and so on. If you wish to read a specific bit of a number, Arduino has an inbuilt method for it. bitRead(x, index) where, x is the number whose bits you are reading, index is the bit to read. 0 corresponds to least significant (right-most) bit, and so on. This function returns either 0 or 1 depending on the value of that bit in that number. The following example will illustrate the use of this function − void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(); int x = 8; Serial.println(bitRead(x,0)); Serial.println(bitRead(x,1)); Serial.println(bitRead(x,2)); Serial.println(bitRead(x,3)); Serial.println(bitRead(x,4)); Serial.println(bitRead(x,5)); Serial.println(bitRead(x,6)); Serial.println(bitRead(x,7)); } void loop() { // put your main code here, to run repeatedly: } The Serial Monitor output is shown below − As you can see, only the bit in position 3 is 1, while all others are 0, which corresponds to the binary representation of 8: 0b00001000
[ { "code": null, "e": 1287, "s": 1062, "text": "Each number has a specific binary representation. For example, 8 can be represented as 0b1000, 15 can be represented as 0b1111, and so on. If you wish to read a specific bit of a number, Arduino has an inbuilt method for it." }, { "code": null, "e": 1305, "s": 1287, "text": "bitRead(x, index)" }, { "code": null, "e": 1446, "s": 1305, "text": "where, x is the number whose bits you are reading, index is the bit to read. 0 corresponds to least significant (right-most) bit, and so on." }, { "code": null, "e": 1533, "s": 1446, "text": "This function returns either 0 or 1 depending on the value of that bit in that number." }, { "code": null, "e": 1598, "s": 1533, "text": "The following example will illustrate the use of this function −" }, { "code": null, "e": 2050, "s": 1598, "text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n int x = 8;\n\n Serial.println(bitRead(x,0));\n Serial.println(bitRead(x,1));\n Serial.println(bitRead(x,2));\n Serial.println(bitRead(x,3));\n Serial.println(bitRead(x,4));\n Serial.println(bitRead(x,5));\n Serial.println(bitRead(x,6));\n Serial.println(bitRead(x,7));\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 2093, "s": 2050, "text": "The Serial Monitor output is shown below −" }, { "code": null, "e": 2230, "s": 2093, "text": "As you can see, only the bit in position 3 is 1, while all others are 0, which corresponds to the binary representation of 8: 0b00001000" } ]
Don’t Use Recursion In Python Any More | by Christopher Tao | Towards Data Science
I was such a programmer who likes recursive functions very much before, simply because it is very cool and can be used to show off my programming skills and intelligence. However, in most of the circumstances, recursive functions have very high complexity that we should avoid using. One of the much better solutions is to use Dynamic Planning when possible, which is probably the best way to solve a problem that can be divided into sub-problems. One of my previous articles has illustrated the power of Dynamic Planning. towardsdatascience.com However, in this article, I’m going to introduce another technique in Python that can be utilised as an alternative to the recursive function. It won’t outperform Dynamic Planning, but much easier in term of thinking. In other words, we may sometimes be struggling to make Dynamic Planning works because of the abstraction of the ideas, but it will be much easier to use closure. First of all, let me use a simple example to demonstrate what is a closure in Python. Look at the function below: def outer(): x = 1 def inner(): print(f'x in outer function: {x}') return inner The function outer is defined with another function inner inside itself, and the function outer returns the function inner as the “return value” of the function. In this case, the nested function is called a closure in Python. If we check the “return value” of the outer function, we will find that the returned value is a function. What does closure do? Because it returned a function, we can run this function, of course. OK, we can see that the inner function can access variables defined in the outer function. Usually, we don’t use closure in such a way shown as above, because it is kind of ugly. We usually want to define another function to hold the function returned by the closure. Therefore, we can also say that in a Python closure, we defined a function that defines functions. How can we use a closure to replace a recursive then? Don’t be too hurry. Let’s have a look at another problem here, which is accessing outer variables from the inner function. def outer(): x = 1 def inner(): print(f'x in outer function (before modifying): {x}') x += 1 print(f'x in outer function (after modifying): {x}') return inner In the closure above-shown, we want to add 1 to the outer variable x in the inner function. However, this won’t work straightforward. By default, you won’t be able to access the outer variable from the inner function. However, just like how we define a global variable in Python, we can tell the inner function of a closure that the variable should not be considered as a “local variable”, by using the nonlocal keyword. def outer(): x = 1 def inner(): nonlocal x print(f'x in outer function (before modifying): {x}') x += 1 print(f'x in outer function (after modifying): {x}') return inner Now, let’s say we want to add the variable x by 1 for five times. We can simply write a for loop to achieve this. f = outer()for i in range(5): print(f'Run {i+1}') f() print('\n') Fibonacci is commonly used as a “hello world” example of recursive functions. If you don’t remember it, don’t worry, it is pretty simple to be explained. A Fibonacci sequence is a series of numbers that every number is the sum of the two numbers before it. The first two numbers, X0 and X1, are special. They are 0 and 1 respectively. Since X2, the patter is as above-mentioned, it is the sum of X0 and X1, so X2=1. Then, X3 is X1 + X2 =2, X4 is X2 + X3=3, X5 is X3 + X4 = 5, and so on. The recursive function requires us to think reversely from the “current scenario” to the “previous scenario”, and eventually what are the terminate conditions. However, by using the closure, we can think about the problem more naturally. See the code below that the Fibonacci function is implemented using a closure. def fib(): x1 = 0 x2 = 1 def get_next_number(): nonlocal x1, x2 x3 = x1 + x2 x1, x2 = x2, x3 return x3 return get_next_number We know that the Fibonacci starts with two special number X0=0 and X1=1, so we just simply define them in the outer function. Then, the inner function get_next_number is simply return the sum of the two numbers it got from the outer function. Additionally, don’t forget to update X0 and X1 with X1 and X2. In fact, we can simplify the code: ...x3 = x1 + x2x1, x2 = x2, x3return x3 to x0, x1 = x1, x0 + x1return x1 This is updating the two variables first and then return the second, which is equivalent to the previous code snippet. Then, we can use this closure to calculate Fibonacci numbers. For example, we want to show the Fibonacci sequence up to the 20th number. fibonacci = fib()for i in range(2, 21): num = fibonacci() print(f'The {i}th Fibonacci number is {num}') Alright, we knew that we can use closure to replace a recursive function in the previous section. How about the performance? Let’s compare them! Firstly, let’s implement the Fibonacci function using a recursive function. def fib_recursion(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_recursion(n-1) + fib_recursion(n-2) We can verify the function by output the 20th number of the Fibonacci sequence. Then, let’s embed the closure version in a function for comparing purposes. def fib_closure(n): f = fib() for i in range(2, n+1): num = f() return num Now, let’s compare the speed. 2.79ms v.s. 2.75μs. The closure method is 1000x faster than the recursive! The most intuitive reason is that all the temporary values for every level of recursion are stored in the memory separately, but the closure is actually updating the same variables in every loop. Also, there is a depth limitation for recursion. For the closure, because it is basically a for loop, there will not be any constraints. Here is an example of getting the 1000th Fibonacci number That’s indeed a huge number, but the closure method can finish the calculation in about 100 μs, while the recursive function met its limitation. Python closures are very useful not only for replacing the recursive functions. In some cases, it can also replace Python classes with a neater solution, especially there are not too many attributes and methods in a class. Suppose we have a dictionary of students with their exam marks. students = { 'Alice': 98, 'Bob': 67, 'Chris': 85, 'David': 75, 'Ella': 54, 'Fiona': 35, 'Grace': 69} We want to have several functions that help us to filter the students by marks, to put them into different grade classes. However, the criteria might change over time. In this case, we can define a Python closure as follows: def make_student_classifier(lower_bound, upper_bound): def classify_student(exam_dict): return {k:v for (k,v) in exam_dict.items() if lower_bound <= v < upper_bound} return classify_student The closure defines a function that defines other functions based on the parameters passed in dynamically. We will pass the lower bound and upper bound of the grade class, and the closure will return us a function does that. grade_A = make_student_classifier(80, 100)grade_B = make_student_classifier(70, 80)grade_C = make_student_classifier(50, 70)grade_D = make_student_classifier(0, 50) The above code will give us 4 functions that will classify the student to the corresponding grade classes based on the boundaries we gave. Please be noted that we can change the boundary any time to make another function or overwrite current grade functions. Let’s verify the functions now. Very neat! Just bear in mind that we still need to define classes when the case is more complex. In this article, I have introduced a technique called closure in Python. It can be utilised to rewrite recursive functions in most circumstances and outperform the latter to a huge extent. Indeed, closure might not be the best solution for some problems from the performance perspective, especially when Dynamic Planning is applicable. However, it is much easier to come up with. Sometimes Dynamic Planning is a bit overkill when we are not very sensitive to the performance, but closure might be good enough. Closure can also be used to replace some use cases that we may want to define a class to satisfy. It is much neater and elegant in those cases. medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)
[ { "code": null, "e": 331, "s": 47, "text": "I was such a programmer who likes recursive functions very much before, simply because it is very cool and can be used to show off my programming skills and intelligence. However, in most of the circumstances, recursive functions have very high complexity that we should avoid using." }, { "code": null, "e": 570, "s": 331, "text": "One of the much better solutions is to use Dynamic Planning when possible, which is probably the best way to solve a problem that can be divided into sub-problems. One of my previous articles has illustrated the power of Dynamic Planning." }, { "code": null, "e": 593, "s": 570, "text": "towardsdatascience.com" }, { "code": null, "e": 973, "s": 593, "text": "However, in this article, I’m going to introduce another technique in Python that can be utilised as an alternative to the recursive function. It won’t outperform Dynamic Planning, but much easier in term of thinking. In other words, we may sometimes be struggling to make Dynamic Planning works because of the abstraction of the ideas, but it will be much easier to use closure." }, { "code": null, "e": 1087, "s": 973, "text": "First of all, let me use a simple example to demonstrate what is a closure in Python. Look at the function below:" }, { "code": null, "e": 1183, "s": 1087, "text": "def outer(): x = 1 def inner(): print(f'x in outer function: {x}') return inner" }, { "code": null, "e": 1345, "s": 1183, "text": "The function outer is defined with another function inner inside itself, and the function outer returns the function inner as the “return value” of the function." }, { "code": null, "e": 1516, "s": 1345, "text": "In this case, the nested function is called a closure in Python. If we check the “return value” of the outer function, we will find that the returned value is a function." }, { "code": null, "e": 1607, "s": 1516, "text": "What does closure do? Because it returned a function, we can run this function, of course." }, { "code": null, "e": 1875, "s": 1607, "text": "OK, we can see that the inner function can access variables defined in the outer function. Usually, we don’t use closure in such a way shown as above, because it is kind of ugly. We usually want to define another function to hold the function returned by the closure." }, { "code": null, "e": 1974, "s": 1875, "text": "Therefore, we can also say that in a Python closure, we defined a function that defines functions." }, { "code": null, "e": 2151, "s": 1974, "text": "How can we use a closure to replace a recursive then? Don’t be too hurry. Let’s have a look at another problem here, which is accessing outer variables from the inner function." }, { "code": null, "e": 2340, "s": 2151, "text": "def outer(): x = 1 def inner(): print(f'x in outer function (before modifying): {x}') x += 1 print(f'x in outer function (after modifying): {x}') return inner" }, { "code": null, "e": 2474, "s": 2340, "text": "In the closure above-shown, we want to add 1 to the outer variable x in the inner function. However, this won’t work straightforward." }, { "code": null, "e": 2761, "s": 2474, "text": "By default, you won’t be able to access the outer variable from the inner function. However, just like how we define a global variable in Python, we can tell the inner function of a closure that the variable should not be considered as a “local variable”, by using the nonlocal keyword." }, { "code": null, "e": 2968, "s": 2761, "text": "def outer(): x = 1 def inner(): nonlocal x print(f'x in outer function (before modifying): {x}') x += 1 print(f'x in outer function (after modifying): {x}') return inner" }, { "code": null, "e": 3082, "s": 2968, "text": "Now, let’s say we want to add the variable x by 1 for five times. We can simply write a for loop to achieve this." }, { "code": null, "e": 3157, "s": 3082, "text": "f = outer()for i in range(5): print(f'Run {i+1}') f() print('\\n')" }, { "code": null, "e": 3311, "s": 3157, "text": "Fibonacci is commonly used as a “hello world” example of recursive functions. If you don’t remember it, don’t worry, it is pretty simple to be explained." }, { "code": null, "e": 3644, "s": 3311, "text": "A Fibonacci sequence is a series of numbers that every number is the sum of the two numbers before it. The first two numbers, X0 and X1, are special. They are 0 and 1 respectively. Since X2, the patter is as above-mentioned, it is the sum of X0 and X1, so X2=1. Then, X3 is X1 + X2 =2, X4 is X2 + X3=3, X5 is X3 + X4 = 5, and so on." }, { "code": null, "e": 3882, "s": 3644, "text": "The recursive function requires us to think reversely from the “current scenario” to the “previous scenario”, and eventually what are the terminate conditions. However, by using the closure, we can think about the problem more naturally." }, { "code": null, "e": 3961, "s": 3882, "text": "See the code below that the Fibonacci function is implemented using a closure." }, { "code": null, "e": 4127, "s": 3961, "text": "def fib(): x1 = 0 x2 = 1 def get_next_number(): nonlocal x1, x2 x3 = x1 + x2 x1, x2 = x2, x3 return x3 return get_next_number" }, { "code": null, "e": 4370, "s": 4127, "text": "We know that the Fibonacci starts with two special number X0=0 and X1=1, so we just simply define them in the outer function. Then, the inner function get_next_number is simply return the sum of the two numbers it got from the outer function." }, { "code": null, "e": 4468, "s": 4370, "text": "Additionally, don’t forget to update X0 and X1 with X1 and X2. In fact, we can simplify the code:" }, { "code": null, "e": 4508, "s": 4468, "text": "...x3 = x1 + x2x1, x2 = x2, x3return x3" }, { "code": null, "e": 4511, "s": 4508, "text": "to" }, { "code": null, "e": 4541, "s": 4511, "text": "x0, x1 = x1, x0 + x1return x1" }, { "code": null, "e": 4660, "s": 4541, "text": "This is updating the two variables first and then return the second, which is equivalent to the previous code snippet." }, { "code": null, "e": 4797, "s": 4660, "text": "Then, we can use this closure to calculate Fibonacci numbers. For example, we want to show the Fibonacci sequence up to the 20th number." }, { "code": null, "e": 4907, "s": 4797, "text": "fibonacci = fib()for i in range(2, 21): num = fibonacci() print(f'The {i}th Fibonacci number is {num}')" }, { "code": null, "e": 5052, "s": 4907, "text": "Alright, we knew that we can use closure to replace a recursive function in the previous section. How about the performance? Let’s compare them!" }, { "code": null, "e": 5128, "s": 5052, "text": "Firstly, let’s implement the Fibonacci function using a recursive function." }, { "code": null, "e": 5275, "s": 5128, "text": "def fib_recursion(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_recursion(n-1) + fib_recursion(n-2)" }, { "code": null, "e": 5355, "s": 5275, "text": "We can verify the function by output the 20th number of the Fibonacci sequence." }, { "code": null, "e": 5431, "s": 5355, "text": "Then, let’s embed the closure version in a function for comparing purposes." }, { "code": null, "e": 5522, "s": 5431, "text": "def fib_closure(n): f = fib() for i in range(2, n+1): num = f() return num" }, { "code": null, "e": 5552, "s": 5522, "text": "Now, let’s compare the speed." }, { "code": null, "e": 5823, "s": 5552, "text": "2.79ms v.s. 2.75μs. The closure method is 1000x faster than the recursive! The most intuitive reason is that all the temporary values for every level of recursion are stored in the memory separately, but the closure is actually updating the same variables in every loop." }, { "code": null, "e": 5960, "s": 5823, "text": "Also, there is a depth limitation for recursion. For the closure, because it is basically a for loop, there will not be any constraints." }, { "code": null, "e": 6018, "s": 5960, "text": "Here is an example of getting the 1000th Fibonacci number" }, { "code": null, "e": 6163, "s": 6018, "text": "That’s indeed a huge number, but the closure method can finish the calculation in about 100 μs, while the recursive function met its limitation." }, { "code": null, "e": 6386, "s": 6163, "text": "Python closures are very useful not only for replacing the recursive functions. In some cases, it can also replace Python classes with a neater solution, especially there are not too many attributes and methods in a class." }, { "code": null, "e": 6450, "s": 6386, "text": "Suppose we have a dictionary of students with their exam marks." }, { "code": null, "e": 6572, "s": 6450, "text": "students = { 'Alice': 98, 'Bob': 67, 'Chris': 85, 'David': 75, 'Ella': 54, 'Fiona': 35, 'Grace': 69}" }, { "code": null, "e": 6797, "s": 6572, "text": "We want to have several functions that help us to filter the students by marks, to put them into different grade classes. However, the criteria might change over time. In this case, we can define a Python closure as follows:" }, { "code": null, "e": 7000, "s": 6797, "text": "def make_student_classifier(lower_bound, upper_bound): def classify_student(exam_dict): return {k:v for (k,v) in exam_dict.items() if lower_bound <= v < upper_bound} return classify_student" }, { "code": null, "e": 7225, "s": 7000, "text": "The closure defines a function that defines other functions based on the parameters passed in dynamically. We will pass the lower bound and upper bound of the grade class, and the closure will return us a function does that." }, { "code": null, "e": 7390, "s": 7225, "text": "grade_A = make_student_classifier(80, 100)grade_B = make_student_classifier(70, 80)grade_C = make_student_classifier(50, 70)grade_D = make_student_classifier(0, 50)" }, { "code": null, "e": 7649, "s": 7390, "text": "The above code will give us 4 functions that will classify the student to the corresponding grade classes based on the boundaries we gave. Please be noted that we can change the boundary any time to make another function or overwrite current grade functions." }, { "code": null, "e": 7681, "s": 7649, "text": "Let’s verify the functions now." }, { "code": null, "e": 7778, "s": 7681, "text": "Very neat! Just bear in mind that we still need to define classes when the case is more complex." }, { "code": null, "e": 7967, "s": 7778, "text": "In this article, I have introduced a technique called closure in Python. It can be utilised to rewrite recursive functions in most circumstances and outperform the latter to a huge extent." }, { "code": null, "e": 8288, "s": 7967, "text": "Indeed, closure might not be the best solution for some problems from the performance perspective, especially when Dynamic Planning is applicable. However, it is much easier to come up with. Sometimes Dynamic Planning is a bit overkill when we are not very sensitive to the performance, but closure might be good enough." }, { "code": null, "e": 8432, "s": 8288, "text": "Closure can also be used to replace some use cases that we may want to define a class to satisfy. It is much neater and elegant in those cases." }, { "code": null, "e": 8443, "s": 8432, "text": "medium.com" } ]
How to implement GROUP by range in MySQL?
To group by range in MySQL, let us first create a table. The query to create a table is as follows mysql> create table GroupByRangeDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > YourRangeValue int - > ); Query OK, 0 rows affected (0.78 sec) Now you can insert some records in the table using insert command. The query is as follows mysql> insert into GroupByRangeDemo(YourRangeValue) values(1); Query OK, 1 row affected (0.14 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(7); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(9); Query OK, 1 row affected (0.14 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(23); Query OK, 1 row affected (0.13 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(33); Query OK, 1 row affected (0.15 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(35); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupByRangeDemo(YourRangeValue) values(1017); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement. The query is as follows mysql> select *from GroupByRangeDemo; The following is the output +----+----------------+ | Id | YourRangeValue | +----+----------------+ | 1 | 1 | | 2 | 7 | | 3 | 9 | | 4 | 23 | | 5 | 33 | | 6 | 35 | | 7 | 1017 | +----+----------------+ 7 rows in set (0.04 sec) Here is the query to group by range mysql> select round(YourRangeValue / 10), count(YourRangeValue) from GroupByRangeDemo where YourRangeValue < 40 group by round(YourRangeValue / 10) - > union - > select '40+', count(YourRangeValue) from GroupByRangeDemo where YourRangeValue >= 40; The following is the output +----------------------------+-----------------------+ | round(YourRangeValue / 10) | count(YourRangeValue) | +----------------------------+-----------------------+ | 0 | 1 | | 1 | 2 | | 2 | 1 | | 3 | 1 | | 4 | 1 | | 40+ | 1 | +----------------------------+-----------------------+ 6 rows in set (0.08 sec)
[ { "code": null, "e": 1161, "s": 1062, "text": "To group by range in MySQL, let us first create a table. The query to create a table is as follows" }, { "code": null, "e": 1331, "s": 1161, "text": "mysql> create table GroupByRangeDemo\n - > (\n - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > YourRangeValue int\n - > );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1398, "s": 1331, "text": "Now you can insert some records in the table using insert command." }, { "code": null, "e": 1422, "s": 1398, "text": "The query is as follows" }, { "code": null, "e": 2121, "s": 1422, "text": "mysql> insert into GroupByRangeDemo(YourRangeValue) values(1);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(7);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(9);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(23);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(33);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(35);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into GroupByRangeDemo(YourRangeValue) values(1017);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2180, "s": 2121, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2204, "s": 2180, "text": "The query is as follows" }, { "code": null, "e": 2242, "s": 2204, "text": "mysql> select *from GroupByRangeDemo;" }, { "code": null, "e": 2270, "s": 2242, "text": "The following is the output" }, { "code": null, "e": 2559, "s": 2270, "text": "+----+----------------+\n| Id | YourRangeValue |\n+----+----------------+\n| 1 | 1 |\n| 2 | 7 |\n| 3 | 9 |\n| 4 | 23 |\n| 5 | 33 |\n| 6 | 35 |\n| 7 | 1017 |\n+----+----------------+\n7 rows in set (0.04 sec)" }, { "code": null, "e": 2595, "s": 2559, "text": "Here is the query to group by range" }, { "code": null, "e": 2849, "s": 2595, "text": "mysql> select round(YourRangeValue / 10), count(YourRangeValue) from GroupByRangeDemo where YourRangeValue < 40 group by round(YourRangeValue / 10)\n - > union\n - > select '40+', count(YourRangeValue) from GroupByRangeDemo where YourRangeValue >= 40;" }, { "code": null, "e": 2877, "s": 2849, "text": "The following is the output" }, { "code": null, "e": 3452, "s": 2877, "text": "+----------------------------+-----------------------+\n| round(YourRangeValue / 10) | count(YourRangeValue) |\n+----------------------------+-----------------------+\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 1 |\n| 40+ | 1 |\n+----------------------------+-----------------------+\n6 rows in set (0.08 sec)" } ]
How to change date time format in HTML5?
The date-time format can be changed by using custom HTML5 elements. If we wish to change or override existing Html tags then we can do so with the help of shadow DOM. We can make customizable tags like − <date-timeformatchange ></ date-timeformatchange> Here is an example − <date-timeformatchange format=”dd/mm/yyyy ></ date-timeformatchange> However, E10 and older versions do not support customizable tags; however, all newer versions support customizable tags.
[ { "code": null, "e": 1229, "s": 1062, "text": "The date-time format can be changed by using custom HTML5 elements. If we wish to change or override existing Html tags then we can do so with the help of shadow DOM." }, { "code": null, "e": 1266, "s": 1229, "text": "We can make customizable tags like −" }, { "code": null, "e": 1316, "s": 1266, "text": "<date-timeformatchange ></ date-timeformatchange>" }, { "code": null, "e": 1337, "s": 1316, "text": "Here is an example −" }, { "code": null, "e": 1406, "s": 1337, "text": "<date-timeformatchange format=”dd/mm/yyyy ></ date-timeformatchange>" }, { "code": null, "e": 1527, "s": 1406, "text": "However, E10 and older versions do not support customizable tags; however, all newer versions support customizable tags." } ]
Demonstrating variable-length arguments in Java
A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required. A program that demonstrates this is given as follows: Live Demo public class Demo { public static void Varargs(String... str) { System.out.println("\nNumber of arguments are: " + str.length); System.out.println("The argument values are: "); for (String s : str) System.out.println(s); } public static void main(String args[]) { Varargs("Apple", "Mango", "Pear"); Varargs(); Varargs("Magic"); } } Number of arguments are: 3 The argument values are: Apple Mango Pear Number of arguments are: 0 The argument values are: Number of arguments are: 1 The argument values are: Magic Now let us understand the above program. The method Varargs() in class Demo has variable-length arguments of type String. This method prints the number of arguments as well as their values. A code snippet which demonstrates this is as follows: public static void Varargs(String... str) { System.out.println("\nNumber of arguments are: " + str.length ); System.out.println("The argument values are: "); for (String s : str) System.out.println(s); } In main() method, the method Varargs() is called with different argument lists. A code snippet which demonstrates this is as follows: public static void main(String args[]) { Varargs("Apple", "MAngo", "Pear"); Varargs(); Varargs("Magic"); }
[ { "code": null, "e": 1345, "s": 1062, "text": "A method with variable length arguments(Varargs) in Java can have zero or multiple arguments. Variable length arguments are most useful when the number of arguments to be passed to the method is not known beforehand. They also reduce the code as overloaded methods are not required." }, { "code": null, "e": 1399, "s": 1345, "text": "A program that demonstrates this is given as follows:" }, { "code": null, "e": 1410, "s": 1399, "text": " Live Demo" }, { "code": null, "e": 1799, "s": 1410, "text": "public class Demo {\n public static void Varargs(String... str) {\n System.out.println(\"\\nNumber of arguments are: \" + str.length);\n System.out.println(\"The argument values are: \");\n for (String s : str)\n System.out.println(s);\n }\n public static void main(String args[]) {\n Varargs(\"Apple\", \"Mango\", \"Pear\");\n Varargs();\n Varargs(\"Magic\");\n }\n}" }, { "code": null, "e": 1980, "s": 1799, "text": "Number of arguments are: 3\nThe argument values are:\nApple\nMango\nPear\n\nNumber of arguments are: 0\nThe argument values are:\n\nNumber of arguments are: 1\nThe argument values are:\nMagic" }, { "code": null, "e": 2021, "s": 1980, "text": "Now let us understand the above program." }, { "code": null, "e": 2224, "s": 2021, "text": "The method Varargs() in class Demo has variable-length arguments of type String. This method prints the number of arguments as well as their values. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2443, "s": 2224, "text": "public static void Varargs(String... str) {\n System.out.println(\"\\nNumber of arguments are: \" + str.length );\n System.out.println(\"The argument values are: \");\n for (String s : str)\n System.out.println(s);\n}" }, { "code": null, "e": 2577, "s": 2443, "text": "In main() method, the method Varargs() is called with different argument lists. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2693, "s": 2577, "text": "public static void main(String args[]) {\n Varargs(\"Apple\", \"MAngo\", \"Pear\");\n Varargs();\n Varargs(\"Magic\");\n}" } ]
Print the pattern | Set-1 | Practice | GeeksforGeeks
You a given a number N. You need to print the pattern for the given value of N. for N = 2 the pattern will be 2 2 1 1 2 1 for N = 3 the pattern will be 3 3 3 2 2 2 1 1 1 3 3 2 2 1 1 3 2 1 Example 1: Input: 2 Output: 2 2 1 1 $2 1 $ Example 2: Input: 3 Output: 3 3 3 2 2 2 1 1 1 $3 3 2 2 1 1 $3 2 1 $ Your Task: Since this is a function problem, you don't need to worry about the testcases. Your task is to complete the function printPat which takes one argument 'N' denoting the length of the pattern. Note : Instead of printing new line print a "$" without quotes. Constraints: 1 <= N <= 40 Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. 0 vishalsinghrajput21 minutes ago def printPat(n): k=0 temp=n result = "" for i in range(0,n,1): for j in range(0,(n*(n-i)),1): if k< (n-i): result+=str(temp)+" " k+=1 else: temp-=1 if temp>0: result+=str(temp)+" " k=1 k=0 temp=n result+="$" return result 0 aahshis1613 hours ago def printPat(n): ret = '' for i in range(n,0,-1): for j in range(n,0,-1): ret += i*(str(j) + ' ') ret += '$' return ret +1 radhakrishna9121rk6 days ago python solution: def printPat(n): #Code here s="" for i in range(n,0,-1): for j in range(n,0,-1): s+=(str(j)+' ')*i s+="$" return s print(printPat(3)) #i passed3 value 0 ejlungay6 days ago Python solution def printPat(n): result = "" nn = n for i in range(n): for k in range(n, 0, -1): for j in range(nn, 0, -1): result += str(k) + " " result += "$" nn -= 1 return result 0 sarajadhav120520091 week ago C++ Solution: void printPat(int n) { const int input = n; for (int i = 1; i <= input; i++) { int copied = input; while (copied > 0) { for (int i = n; i > 0; i--) //3 { cout << copied << " "; } copied--; } cout << "$"; n--; } } 0 sharmahariom342881 week ago C solution : void printPat(int n) { int x, y, z; for (x = n; x >= 1; x--) { for (y = n; y >= 1; y--) { for (z = 1; z <= x; z++) { printf("%d ", y); } } printf("$"); } } 0 monsotal2 weeks ago void printPat(int n) { for(int t =0 ; t<n ; t++){ for(int k =n ; k>0 ;k--){ for(int i =n ; i>t ; i--){ System.out.print(k+" "); } } System.out.print("$"); } } +1 monsotal2 weeks ago void printPat(int n) { for(int t =0 ; t<n ; t++){ for(int k =n ; k>0 ;k--){ for(int i =n ; i>t ; i--){ System.out.print(k+" "); } } System.out.print("$"); } } 0 monsotal2 weeks ago class GfG{ void printPat(int n) { for(int t =0 ; t<n ; t++){ for(int k =n ; k>0 ;k--){ for(int i =n ; i>t ; i--){ System.out.print(k+" "); } } System.out.print("$"); } }} 0 monsotal2 weeks ago Java: class GfG { void printPat(int n) { for(int t =0 ; t<n ; t++){ for(int k =n ; k>0 ;k--){ for(int i =n ; i>t ; i--){ System.out.print(k+" "); } } System.out.print("$"); } } } 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": 428, "s": 238, "text": "You a given a number N. You need to print the pattern for the given value of N.\nfor N = 2 the pattern will be \n2 2 1 1\n2 1\nfor N = 3 the pattern will be \n3 3 3 2 2 2 1 1 1\n3 3 2 2 1 1\n3 2 1" }, { "code": null, "e": 439, "s": 428, "text": "Example 1:" }, { "code": null, "e": 473, "s": 439, "text": "Input: 2\nOutput:\n2 2 1 1 $2 1 $\n\n" }, { "code": null, "e": 484, "s": 473, "text": "Example 2:" }, { "code": null, "e": 542, "s": 484, "text": "Input: 3\nOutput:\n3 3 3 2 2 2 1 1 1 $3 3 2 2 1 1 $3 2 1 $\n" }, { "code": null, "e": 810, "s": 544, "text": "Your Task:\nSince this is a function problem, you don't need to worry about the testcases. Your task is to complete the function printPat which takes one argument 'N' denoting the length of the pattern.\nNote : Instead of printing new line print a \"$\" without quotes." }, { "code": null, "e": 836, "s": 810, "text": "Constraints:\n1 <= N <= 40" }, { "code": null, "e": 1146, "s": 836, "text": "\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1148, "s": 1146, "text": "0" }, { "code": null, "e": 1180, "s": 1148, "text": "vishalsinghrajput21 minutes ago" }, { "code": null, "e": 1584, "s": 1180, "text": "def printPat(n):\n\n k=0\n temp=n\n result = \"\"\n for i in range(0,n,1):\n for j in range(0,(n*(n-i)),1):\n if k< (n-i):\n result+=str(temp)+\" \"\n k+=1\n else:\n temp-=1 \n if temp>0:\n result+=str(temp)+\" \"\n k=1\n k=0\n temp=n\n result+=\"$\"\n return result" }, { "code": null, "e": 1586, "s": 1584, "text": "0" }, { "code": null, "e": 1608, "s": 1586, "text": "aahshis1613 hours ago" }, { "code": null, "e": 1754, "s": 1608, "text": "def printPat(n): ret = '' for i in range(n,0,-1): for j in range(n,0,-1): ret += i*(str(j) + ' ') ret += '$'" }, { "code": null, "e": 1768, "s": 1754, "text": " return ret" }, { "code": null, "e": 1771, "s": 1768, "text": "+1" }, { "code": null, "e": 1800, "s": 1771, "text": "radhakrishna9121rk6 days ago" }, { "code": null, "e": 1817, "s": 1800, "text": "python solution:" }, { "code": null, "e": 2021, "s": 1817, "text": "def printPat(n):\n #Code here\n s=\"\"\n for i in range(n,0,-1):\n for j in range(n,0,-1):\n s+=(str(j)+' ')*i\n s+=\"$\"\n return s\n print(printPat(3)) #i passed3 value" }, { "code": null, "e": 2023, "s": 2021, "text": "0" }, { "code": null, "e": 2042, "s": 2023, "text": "ejlungay6 days ago" }, { "code": null, "e": 2058, "s": 2042, "text": "Python solution" }, { "code": null, "e": 2302, "s": 2058, "text": "def printPat(n):\n result = \"\"\n nn = n\n for i in range(n):\n for k in range(n, 0, -1):\n for j in range(nn, 0, -1):\n result += str(k) + \" \"\n result += \"$\"\n nn -= 1\n \n return result" }, { "code": null, "e": 2304, "s": 2302, "text": "0" }, { "code": null, "e": 2333, "s": 2304, "text": "sarajadhav120520091 week ago" }, { "code": null, "e": 2347, "s": 2333, "text": "C++ Solution:" }, { "code": null, "e": 2689, "s": 2347, "text": "void printPat(int n)\n{\n const int input = n;\n\n for (int i = 1; i <= input; i++)\n {\n int copied = input;\n while (copied > 0)\n {\n for (int i = n; i > 0; i--) //3\n {\n cout << copied << \" \";\n }\n copied--;\n }\n cout << \"$\";\n n--;\n }\n}" }, { "code": null, "e": 2691, "s": 2689, "text": "0" }, { "code": null, "e": 2719, "s": 2691, "text": "sharmahariom342881 week ago" }, { "code": null, "e": 2732, "s": 2719, "text": "C solution :" }, { "code": null, "e": 2995, "s": 2734, "text": "void printPat(int n)\n{\n int x, y, z;\n \n for (x = n; x >= 1; x--)\n {\n for (y = n; y >= 1; y--)\n {\n for (z = 1; z <= x; z++)\n {\n printf(\"%d \", y);\n }\n }\n printf(\"$\");\n }\n}" }, { "code": null, "e": 2997, "s": 2995, "text": "0" }, { "code": null, "e": 3017, "s": 2997, "text": "monsotal2 weeks ago" }, { "code": null, "e": 3289, "s": 3017, "text": " void printPat(int n) {\n\n for(int t =0 ; t<n ; t++){\n for(int k =n ; k>0 ;k--){\n for(int i =n ; i>t ; i--){\n System.out.print(k+\" \");\n }\n }\n System.out.print(\"$\");\n\n }\n }" }, { "code": null, "e": 3292, "s": 3289, "text": "+1" }, { "code": null, "e": 3312, "s": 3292, "text": "monsotal2 weeks ago" }, { "code": null, "e": 3584, "s": 3312, "text": " void printPat(int n) {\n\n for(int t =0 ; t<n ; t++){\n for(int k =n ; k>0 ;k--){\n for(int i =n ; i>t ; i--){\n System.out.print(k+\" \");\n }\n }\n System.out.print(\"$\");\n\n }\n }" }, { "code": null, "e": 3586, "s": 3584, "text": "0" }, { "code": null, "e": 3606, "s": 3586, "text": "monsotal2 weeks ago" }, { "code": null, "e": 3867, "s": 3606, "text": "class GfG{ void printPat(int n) { for(int t =0 ; t<n ; t++){ for(int k =n ; k>0 ;k--){ for(int i =n ; i>t ; i--){ System.out.print(k+\" \"); } } System.out.print(\"$\");" }, { "code": null, "e": 3881, "s": 3867, "text": " } }}" }, { "code": null, "e": 3883, "s": 3881, "text": "0" }, { "code": null, "e": 3903, "s": 3883, "text": "monsotal2 weeks ago" }, { "code": null, "e": 3909, "s": 3903, "text": "Java:" }, { "code": null, "e": 4212, "s": 3911, "text": "class GfG\n{\n void printPat(int n)\n {\n \n for(int t =0 ; t<n ; t++){\n for(int k =n ; k>0 ;k--){\n for(int i =n ; i>t ; i--){\n System.out.print(k+\" \");\n }\n }\n System.out.print(\"$\");\n\n }\n }\n}" }, { "code": null, "e": 4358, "s": 4212, "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": 4394, "s": 4358, "text": " Login to access your submissions. " }, { "code": null, "e": 4404, "s": 4394, "text": "\nProblem\n" }, { "code": null, "e": 4414, "s": 4404, "text": "\nContest\n" }, { "code": null, "e": 4477, "s": 4414, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4625, "s": 4477, "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": 4833, "s": 4625, "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": 4939, "s": 4833, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Abstract Factory Method - Python Design Patterns - GeeksforGeeks
25 Feb, 2022 Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try to abstract the creation of the objects depending on the logic, business, platform choice, etc. Imagine you want to join one of the elite batches of GeeksforGeeks. So, you will go there and ask about the Courses available, their Fee structure, their timings, and other important things. They will simply look at their system and will give you all the information you required. Looks simple? Think about the developers how they make the system so organized and how their website is so lubricative. Developers will make unique classes for each course which will contain its properties like Fee structure, timings, and other things. But how they will call them and how will they instantiate their objects? Here arises the problem, suppose initially there are only 3-4 courses available at GeeksforGeeks, but later they added 5 new courses. So, we have to manually instantiate their objects which is not a good thing according to the developer’s side. Abstract Factory Diagrammatic representation of Problems without using Abstract Factory Method Note: Following code is written without using the abstract factory method Python3 # Python Code for object# oriented concepts without# using the Abstract factory# method in class class DSA: """ Class for Data Structure and Algorithms """ def price(self): return 11000 def __str__(self): return "DSA" class STL: """Class for Standard Template Library""" def price(self): return 8000 def __str__(self): return "STL" class SDE: """Class for Software Development Engineer""" def price(self): return 15000 def __str__(self): return 'SDE' # main methodif __name__ == "__main__": sde = SDE() # object for SDE class dsa = DSA() # object for DSA class stl = STL() # object for STL class print(f'Name of the course is {sde} and its price is {sde.price()}') print(f'Name of the course is {dsa} and its price is {dsa.price()}') print(f'Name of the course is {stl} and its price is {stl.price()}') Its solution is to replace the straightforward object construction calls with calls to the special abstract factory method. Actually, there will be no difference in the object creation but they are being called within the factory method. Now we will create a unique class whose name is Course_At_GFG which will handle all the object instantiation automatically. Now, we don’t have to worry about how many courses we are adding after some time. solution using abstract factory pattern Python3 # Python Code for object# oriented concepts using# the abstract factory# design pattern import random class Course_At_GFG: """ GeeksforGeeks portal for courses """ def __init__(self, courses_factory = None): """course factory is out abstract factory""" self.course_factory = courses_factory def show_course(self): """creates and shows courses using the abstract factory""" course = self.course_factory() print(f'We have a course named {course}') print(f'its price is {course.Fee()}') class DSA: """Class for Data Structure and Algorithms""" def Fee(self): return 11000 def __str__(self): return "DSA" class STL: """Class for Standard Template Library""" def Fee(self): return 8000 def __str__(self): return "STL" class SDE: """Class for Software Development Engineer""" def Fee(self): return 15000 def __str__(self): return 'SDE' def random_course(): """A random class for choosing the course""" return random.choice([SDE, STL, DSA])() if __name__ == "__main__": course = Course_At_GFG(random_course) for i in range(5): course.show_course() Let’s look at the class diagram considering the example of Courses at GeeksforGeeks. Fee structure of all the available courses at GeeksforGeeks class diagram for the abstract factory pattern Timings of all the available courses at GeeksforGeeks class diagram 2 abstract method pattern This pattern is particularly useful when the client doesn’t know exactly what type to create. It is easy to introduce new variants of the products without breaking the existing client code.Products which we are getting from the factory are surely compatible with each other. It is easy to introduce new variants of the products without breaking the existing client code. Products which we are getting from the factory are surely compatible with each other. Our simple code may become complicated due to the existence of a lot of classes.We end up with a huge number of small files i.e, cluttering of files. Our simple code may become complicated due to the existence of a lot of classes. We end up with a huge number of small files i.e, cluttering of files. Most commonly, abstract factory method pattern is found in the sheet metal stamping equipment used in the manufacture of automobiles.It can be used in a system that has to process reports of different categories such as reports related to input, output, and intermediate transactions. Most commonly, abstract factory method pattern is found in the sheet metal stamping equipment used in the manufacture of automobiles. It can be used in a system that has to process reports of different categories such as reports related to input, output, and intermediate transactions. simmytarika5 sweetyty anikakapoor kimjones python-design-pattern 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 ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24204, "s": 24176, "text": "\n25 Feb, 2022" }, { "code": null, "e": 24649, "s": 24204, "text": "Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try to abstract the creation of the objects depending on the logic, business, platform choice, etc." }, { "code": null, "e": 25050, "s": 24649, "text": "Imagine you want to join one of the elite batches of GeeksforGeeks. So, you will go there and ask about the Courses available, their Fee structure, their timings, and other important things. They will simply look at their system and will give you all the information you required. Looks simple? Think about the developers how they make the system so organized and how their website is so lubricative." }, { "code": null, "e": 25256, "s": 25050, "text": "Developers will make unique classes for each course which will contain its properties like Fee structure, timings, and other things. But how they will call them and how will they instantiate their objects?" }, { "code": null, "e": 25502, "s": 25256, "text": "Here arises the problem, suppose initially there are only 3-4 courses available at GeeksforGeeks, but later they added 5 new courses. So, we have to manually instantiate their objects which is not a good thing according to the developer’s side. " }, { "code": null, "e": 25519, "s": 25502, "text": "Abstract Factory" }, { "code": null, "e": 25597, "s": 25519, "text": "Diagrammatic representation of Problems without using Abstract Factory Method" }, { "code": null, "e": 25672, "s": 25597, "text": "Note: Following code is written without using the abstract factory method " }, { "code": null, "e": 25680, "s": 25672, "text": "Python3" }, { "code": "# Python Code for object# oriented concepts without# using the Abstract factory# method in class class DSA: \"\"\" Class for Data Structure and Algorithms \"\"\" def price(self): return 11000 def __str__(self): return \"DSA\" class STL: \"\"\"Class for Standard Template Library\"\"\" def price(self): return 8000 def __str__(self): return \"STL\" class SDE: \"\"\"Class for Software Development Engineer\"\"\" def price(self): return 15000 def __str__(self): return 'SDE' # main methodif __name__ == \"__main__\": sde = SDE() # object for SDE class dsa = DSA() # object for DSA class stl = STL() # object for STL class print(f'Name of the course is {sde} and its price is {sde.price()}') print(f'Name of the course is {dsa} and its price is {dsa.price()}') print(f'Name of the course is {stl} and its price is {stl.price()}')", "e": 26590, "s": 25680, "text": null }, { "code": null, "e": 27034, "s": 26590, "text": "Its solution is to replace the straightforward object construction calls with calls to the special abstract factory method. Actually, there will be no difference in the object creation but they are being called within the factory method. Now we will create a unique class whose name is Course_At_GFG which will handle all the object instantiation automatically. Now, we don’t have to worry about how many courses we are adding after some time." }, { "code": null, "e": 27074, "s": 27034, "text": "solution using abstract factory pattern" }, { "code": null, "e": 27082, "s": 27074, "text": "Python3" }, { "code": "# Python Code for object# oriented concepts using# the abstract factory# design pattern import random class Course_At_GFG: \"\"\" GeeksforGeeks portal for courses \"\"\" def __init__(self, courses_factory = None): \"\"\"course factory is out abstract factory\"\"\" self.course_factory = courses_factory def show_course(self): \"\"\"creates and shows courses using the abstract factory\"\"\" course = self.course_factory() print(f'We have a course named {course}') print(f'its price is {course.Fee()}') class DSA: \"\"\"Class for Data Structure and Algorithms\"\"\" def Fee(self): return 11000 def __str__(self): return \"DSA\" class STL: \"\"\"Class for Standard Template Library\"\"\" def Fee(self): return 8000 def __str__(self): return \"STL\" class SDE: \"\"\"Class for Software Development Engineer\"\"\" def Fee(self): return 15000 def __str__(self): return 'SDE' def random_course(): \"\"\"A random class for choosing the course\"\"\" return random.choice([SDE, STL, DSA])() if __name__ == \"__main__\": course = Course_At_GFG(random_course) for i in range(5): course.show_course()", "e": 28284, "s": 27082, "text": null }, { "code": null, "e": 28431, "s": 28284, "text": "Let’s look at the class diagram considering the example of Courses at GeeksforGeeks. Fee structure of all the available courses at GeeksforGeeks " }, { "code": null, "e": 28478, "s": 28431, "text": "class diagram for the abstract factory pattern" }, { "code": null, "e": 28534, "s": 28478, "text": "Timings of all the available courses at GeeksforGeeks " }, { "code": null, "e": 28574, "s": 28534, "text": "class diagram 2 abstract method pattern" }, { "code": null, "e": 28669, "s": 28574, "text": "This pattern is particularly useful when the client doesn’t know exactly what type to create. " }, { "code": null, "e": 28850, "s": 28669, "text": "It is easy to introduce new variants of the products without breaking the existing client code.Products which we are getting from the factory are surely compatible with each other." }, { "code": null, "e": 28946, "s": 28850, "text": "It is easy to introduce new variants of the products without breaking the existing client code." }, { "code": null, "e": 29032, "s": 28946, "text": "Products which we are getting from the factory are surely compatible with each other." }, { "code": null, "e": 29182, "s": 29032, "text": "Our simple code may become complicated due to the existence of a lot of classes.We end up with a huge number of small files i.e, cluttering of files." }, { "code": null, "e": 29263, "s": 29182, "text": "Our simple code may become complicated due to the existence of a lot of classes." }, { "code": null, "e": 29333, "s": 29263, "text": "We end up with a huge number of small files i.e, cluttering of files." }, { "code": null, "e": 29618, "s": 29333, "text": "Most commonly, abstract factory method pattern is found in the sheet metal stamping equipment used in the manufacture of automobiles.It can be used in a system that has to process reports of different categories such as reports related to input, output, and intermediate transactions." }, { "code": null, "e": 29752, "s": 29618, "text": "Most commonly, abstract factory method pattern is found in the sheet metal stamping equipment used in the manufacture of automobiles." }, { "code": null, "e": 29904, "s": 29752, "text": "It can be used in a system that has to process reports of different categories such as reports related to input, output, and intermediate transactions." }, { "code": null, "e": 29917, "s": 29904, "text": "simmytarika5" }, { "code": null, "e": 29926, "s": 29917, "text": "sweetyty" }, { "code": null, "e": 29938, "s": 29926, "text": "anikakapoor" }, { "code": null, "e": 29947, "s": 29938, "text": "kimjones" }, { "code": null, "e": 29969, "s": 29947, "text": "python-design-pattern" }, { "code": null, "e": 29976, "s": 29969, "text": "Python" }, { "code": null, "e": 30074, "s": 29976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30083, "s": 30074, "text": "Comments" }, { "code": null, "e": 30096, "s": 30083, "text": "Old Comments" }, { "code": null, "e": 30114, "s": 30096, "text": "Python Dictionary" }, { "code": null, "e": 30149, "s": 30114, "text": "Read a file line by line in Python" }, { "code": null, "e": 30171, "s": 30149, "text": "Enumerate() in Python" }, { "code": null, "e": 30203, "s": 30171, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30245, "s": 30203, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30271, "s": 30245, "text": "Python String | replace()" }, { "code": null, "e": 30308, "s": 30271, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30352, "s": 30308, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30381, "s": 30352, "text": "*args and **kwargs in Python" } ]
C# Program to implement Sleep Method Of Thread
The sleep method of the thread is used to pause the thread for a specific period. If you want to set sleep for some seconds, then use it like the following code snippet − int sleepfor = 2000; Thread.Sleep(sleepfor); You can try to run the following code to implement the sleep method of the thread. Live Demo using System; using System.Threading; namespace MyApplication { class ThreadCreationProgram { public static void CallToChildThread() { Console.WriteLine("Child thread starts"); int sleepfor = 2000; Console.WriteLine("Child Thread Paused for {0} seconds", sleepfor / 1000); Thread.Sleep(sleepfor); Console.WriteLine("Child thread resumes"); } static void Main(string[] args) { ThreadStart childref = new ThreadStart(CallToChildThread); Console.WriteLine("In Main: Creating the Child thread"); Thread childThread = new Thread(childref); childThread.Start(); Console.ReadKey(); } } } In Main: Creating the Child thread Child thread starts Child Thread Paused for 2 seconds Child thread resumes
[ { "code": null, "e": 1144, "s": 1062, "text": "The sleep method of the thread is used to pause the thread for a specific period." }, { "code": null, "e": 1233, "s": 1144, "text": "If you want to set sleep for some seconds, then use it like the following code snippet −" }, { "code": null, "e": 1278, "s": 1233, "text": "int sleepfor = 2000;\nThread.Sleep(sleepfor);" }, { "code": null, "e": 1361, "s": 1278, "text": "You can try to run the following code to implement the sleep method of the thread." }, { "code": null, "e": 1371, "s": 1361, "text": "Live Demo" }, { "code": null, "e": 2072, "s": 1371, "text": "using System;\nusing System.Threading;\nnamespace MyApplication {\n class ThreadCreationProgram {\n public static void CallToChildThread() {\n Console.WriteLine(\"Child thread starts\");\n int sleepfor = 2000;\n Console.WriteLine(\"Child Thread Paused for {0} seconds\", sleepfor / 1000);\n Thread.Sleep(sleepfor);\n Console.WriteLine(\"Child thread resumes\");\n }\n static void Main(string[] args) {\n ThreadStart childref = new ThreadStart(CallToChildThread);\n Console.WriteLine(\"In Main: Creating the Child thread\");\n Thread childThread = new Thread(childref);\n childThread.Start();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2182, "s": 2072, "text": "In Main: Creating the Child thread\nChild thread starts\nChild Thread Paused for 2 seconds\nChild thread resumes" } ]
Compression of IPv6 address - GeeksforGeeks
28 Jun, 2021 IPv6 address is short form of IP address version 6. It is basically a 128 bit address. In IPv6 address, hexadecimal notation is preferred. There are total 8 fields in IPv6 hexadecimal notation and each field consists of 16 bits. Hence, total bits are 8 x 16 = 128 Rules for compression: There are basically three rules for compression: Rule-1: When only 0 (zero) is available in a field then it is removed from the IPv6 address notation. IPv6 = FE82:1234:0:1235:1416:1A12:1B12:1C1F After compression, IPv6 = FE82:1234::1235:1416:1A12:1B12:1C1F Rule-2: When continuous 0s (zeros) are available in IPv6 address notation then all zeros are replaced by ::. IPv6 = FE82:0:0:0:0:1A12:1234:1A12 After compression, IPv6 = FE82::1A12:1234:1A12 Rule-3: When zeros are present in discontinuous places then at only one junction, 0s (zeros) are replaced by ::. IPv6 = 2001:1234:0:0:1A12:0:0:1A13 After compression, IPv6 = 2001:1234::1A12:0:0:1A13 or = 2001:1234:0:0:1A12::1A13 Unspecified Address: When in hexadecimal notation of IPv6 all fields are 0. It is denoted by ::. :: = 0:0:0:0:0:0:0:0 Loop Back Address: When in hexadecimal notation of IPv6 all fields are 0 except the last field and last field value is 1. It is denoted by ::1. ::1 = 0:0:0:0:0:0:0:1 clintra Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments RSA Algorithm in Cryptography TCP Server-Client implementation in C Data encryption standard (DES) | Set 1 Types of Network Topology Types of Transmission Media ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems Page Replacement Algorithms in Operating Systems Data encryption standard (DES) | Set 1
[ { "code": null, "e": 24491, "s": 24463, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24756, "s": 24491, "text": "IPv6 address is short form of IP address version 6. It is basically a 128 bit address. In IPv6 address, hexadecimal notation is preferred. There are total 8 fields in IPv6 hexadecimal notation and each field consists of 16 bits. Hence, total bits are 8 x 16 = 128 " }, { "code": null, "e": 24830, "s": 24756, "text": "Rules for compression: There are basically three rules for compression: " }, { "code": null, "e": 24934, "s": 24830, "text": "Rule-1: When only 0 (zero) is available in a field then it is removed from the IPv6 address notation. " }, { "code": null, "e": 25044, "s": 24936, "text": "IPv6 = FE82:1234:0:1235:1416:1A12:1B12:1C1F\n\nAfter compression,\nIPv6 = FE82:1234::1235:1416:1A12:1B12:1C1F " }, { "code": null, "e": 25159, "s": 25048, "text": "Rule-2: When continuous 0s (zeros) are available in IPv6 address notation then all zeros are replaced by ::. " }, { "code": null, "e": 25245, "s": 25161, "text": "IPv6 = FE82:0:0:0:0:1A12:1234:1A12\n\nAfter compression,\nIPv6 = FE82::1A12:1234:1A12 " }, { "code": null, "e": 25364, "s": 25249, "text": "Rule-3: When zeros are present in discontinuous places then at only one junction, 0s (zeros) are replaced by ::. " }, { "code": null, "e": 25499, "s": 25366, "text": "IPv6 = 2001:1234:0:0:1A12:0:0:1A13\n\nAfter compression,\nIPv6 = 2001:1234::1A12:0:0:1A13\n or\n = 2001:1234:0:0:1A12::1A13 " }, { "code": null, "e": 25602, "s": 25503, "text": "Unspecified Address: When in hexadecimal notation of IPv6 all fields are 0. It is denoted by ::. " }, { "code": null, "e": 25623, "s": 25602, "text": ":: = 0:0:0:0:0:0:0:0" }, { "code": null, "e": 25769, "s": 25623, "text": "Loop Back Address: When in hexadecimal notation of IPv6 all fields are 0 except the last field and last field value is 1. It is denoted by ::1. " }, { "code": null, "e": 25791, "s": 25769, "text": "::1 = 0:0:0:0:0:0:0:1" }, { "code": null, "e": 25801, "s": 25793, "text": "clintra" }, { "code": null, "e": 25819, "s": 25801, "text": "Computer Networks" }, { "code": null, "e": 25827, "s": 25819, "text": "GATE CS" }, { "code": null, "e": 25845, "s": 25827, "text": "Computer Networks" }, { "code": null, "e": 25943, "s": 25845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25952, "s": 25943, "text": "Comments" }, { "code": null, "e": 25965, "s": 25952, "text": "Old Comments" }, { "code": null, "e": 25995, "s": 25965, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 26033, "s": 25995, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26072, "s": 26033, "text": "Data encryption standard (DES) | Set 1" }, { "code": null, "e": 26098, "s": 26072, "text": "Types of Network Topology" }, { "code": null, "e": 26126, "s": 26098, "text": "Types of Transmission Media" }, { "code": null, "e": 26150, "s": 26126, "text": "ACID Properties in DBMS" }, { "code": null, "e": 26171, "s": 26150, "text": "Normal Forms in DBMS" }, { "code": null, "e": 26198, "s": 26171, "text": "Types of Operating Systems" }, { "code": null, "e": 26247, "s": 26198, "text": "Page Replacement Algorithms in Operating Systems" } ]
Bootstrap 4 | Accordion - GeeksforGeeks
14 Oct, 2020 The following example displays a simple accordion by extending the panel component. The use of the data-parent attribute to makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible items is display.There are so many types of Accordion Default Accordion Accordion with icons Accordion with gradient background Accordion with a picture Below you will see each of them in action with the proper example. Example:<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html> <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html> Output:Accordion with changeable icons: This example will show you how to add plus and minus icons in accordion with the help of font-awesome and toggle when you open an accordion with the help of jQuery.Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Bootstrap 4 Accordion </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(".collapse.show").each(function() { $(this).prev(".card-header").find(".fa") .addClass("fa-minus").removeClass("fa-plus"); }); // Toggle plus minus icon on show hide // of collapse element $(".collapse").on('show.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-plus").addClass("fa-minus"); }).on('hide.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-minus").addClass("fa-plus"); }); }); </script></head> <body> <div class="accordion"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button type="button" class="btn btn-link" data-toggle="collapse" data-target="#collapseOne"> <i class="fa fa-plus"></i> GeeksforGeeks </button> </h2> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"> <i class="fa fa-plus"></i> Bootstrap </button> </h2> </div> <div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample"> <div class="card-body"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingThree"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree"> <i class="fa fa-plus"></i> HTML </button> </h2> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample"> <div class="card-body"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html>Output:Accordion with gradient background: This is a simple of accordian with the gradient color effects.<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>Output:Accordion with the picture: In this example the accordion will conatins picture within it. Accordion with changeable icons: This example will show you how to add plus and minus icons in accordion with the help of font-awesome and toggle when you open an accordion with the help of jQuery. Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Bootstrap 4 Accordion </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(".collapse.show").each(function() { $(this).prev(".card-header").find(".fa") .addClass("fa-minus").removeClass("fa-plus"); }); // Toggle plus minus icon on show hide // of collapse element $(".collapse").on('show.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-plus").addClass("fa-minus"); }).on('hide.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-minus").addClass("fa-plus"); }); }); </script></head> <body> <div class="accordion"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button type="button" class="btn btn-link" data-toggle="collapse" data-target="#collapseOne"> <i class="fa fa-plus"></i> GeeksforGeeks </button> </h2> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"> <i class="fa fa-plus"></i> Bootstrap </button> </h2> </div> <div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample"> <div class="card-body"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingThree"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree"> <i class="fa fa-plus"></i> HTML </button> </h2> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample"> <div class="card-body"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Bootstrap 4 Accordion </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(".collapse.show").each(function() { $(this).prev(".card-header").find(".fa") .addClass("fa-minus").removeClass("fa-plus"); }); // Toggle plus minus icon on show hide // of collapse element $(".collapse").on('show.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-plus").addClass("fa-minus"); }).on('hide.bs.collapse', function() { $(this).prev(".card-header").find(".fa") .removeClass("fa-minus").addClass("fa-plus"); }); }); </script></head> <body> <div class="accordion"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class="accordion" id="accordionExample"> <div class="card"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button type="button" class="btn btn-link" data-toggle="collapse" data-target="#collapseOne"> <i class="fa fa-plus"></i> GeeksforGeeks </button> </h2> </div> <div id="collapseOne" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo"> <i class="fa fa-plus"></i> Bootstrap </button> </h2> </div> <div id="collapseTwo" class="collapse show" aria-labelledby="headingTwo" data-parent="#accordionExample"> <div class="card-body"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class="card"> <div class="card-header" id="headingThree"> <h2 class="mb-0"> <button type="button" class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree"> <i class="fa fa-plus"></i> HTML </button> </h2> </div> <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample"> <div class="card-body"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html> Output: Accordion with gradient background: This is a simple of accordian with the gradient color effects. <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html> <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html> Output: Accordion with the picture: In this example the accordion will conatins picture within it. Example:<!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card{ width:600px; } .card-body{ width:400px; float: left; } .right-body{ width:100px; margin:10px; float : right; } img{ width:100px; height:100px; } </style> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> <div class="right-body"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png"> </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> <div class="right-body"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191126170417/logo6.png"> </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> <div class="right-body"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png"> </div> </div> </div> </div> </div> </body> </html> <!DOCTYPE html><html lang="en"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <style> .card{ width:600px; } .card-body{ width:400px; float: left; } .right-body{ width:100px; margin:10px; float : right; } img{ width:100px; height:100px; } </style> <head> <body> <div class="container"> <h2 style="padding-bottom: 15px; color:green;"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#description1"> GeeksforGeeks </a> </div> <div id="description1" class="collapse show" data-parent="#accordion"> <div class="card-body"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> <div class="right-body"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png"> </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description2"> Bootstrap </a> </div> <div id="description2" class="collapse" data-parent="#accordion"> <div class="card-body"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> <div class="right-body"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20191126170417/logo6.png"> </div> </div> </div> <div class="card"> <div class="card-header"> <a class="collapsed card-link" data-toggle="collapse" href="#description3"> HTML </a> </div> <div id="description3" class="collapse" data-parent="#accordion"> <div class="card-body"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> <div class="right-body"> <img src="https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png"> </div> </div> </div> </div> </div> </body> </html> Output:My Personal Notes arrow_drop_upSave AakashYadav4 Bootstrap-4 Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28049, "s": 28021, "text": "\n14 Oct, 2020" }, { "code": null, "e": 28338, "s": 28049, "text": "The following example displays a simple accordion by extending the panel component. The use of the data-parent attribute to makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible items is display.There are so many types of Accordion" }, { "code": null, "e": 28356, "s": 28338, "text": "Default Accordion" }, { "code": null, "e": 28377, "s": 28356, "text": "Accordion with icons" }, { "code": null, "e": 28412, "s": 28377, "text": "Accordion with gradient background" }, { "code": null, "e": 28437, "s": 28412, "text": "Accordion with a picture" }, { "code": null, "e": 28504, "s": 28437, "text": "Below you will see each of them in action with the proper example." }, { "code": null, "e": 31924, "s": 28504, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>", "e": 35336, "s": 31924, "text": null }, { "code": null, "e": 44477, "s": 35336, "text": "Output:Accordion with changeable icons: This example will show you how to add plus and minus icons in accordion with the help of font-awesome and toggle when you open an accordion with the help of jQuery.Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>Bootstrap 4 Accordion </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(\".collapse.show\").each(function() { $(this).prev(\".card-header\").find(\".fa\") .addClass(\"fa-minus\").removeClass(\"fa-plus\"); }); // Toggle plus minus icon on show hide // of collapse element $(\".collapse\").on('show.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-plus\").addClass(\"fa-minus\"); }).on('hide.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-minus\").addClass(\"fa-plus\"); }); }); </script></head> <body> <div class=\"accordion\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class=\"accordion\" id=\"accordionExample\"> <div class=\"card\"> <div class=\"card-header\" id=\"headingOne\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link\" data-toggle=\"collapse\" data-target=\"#collapseOne\"> <i class=\"fa fa-plus\"></i> GeeksforGeeks </button> </h2> </div> <div id=\"collapseOne\" class=\"collapse\" aria-labelledby=\"headingOne\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingTwo\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo\"> <i class=\"fa fa-plus\"></i> Bootstrap </button> </h2> </div> <div id=\"collapseTwo\" class=\"collapse show\" aria-labelledby=\"headingTwo\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingThree\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree\"> <i class=\"fa fa-plus\"></i> HTML </button> </h2> </div> <div id=\"collapseThree\" class=\"collapse\" aria-labelledby=\"headingThree\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html>Output:Accordion with gradient background: This is a simple of accordian with the gradient color effects.<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>Output:Accordion with the picture: In this example the accordion will conatins picture within it." }, { "code": null, "e": 44675, "s": 44477, "text": "Accordion with changeable icons: This example will show you how to add plus and minus icons in accordion with the help of font-awesome and toggle when you open an accordion with the help of jQuery." }, { "code": null, "e": 49809, "s": 44675, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>Bootstrap 4 Accordion </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(\".collapse.show\").each(function() { $(this).prev(\".card-header\").find(\".fa\") .addClass(\"fa-minus\").removeClass(\"fa-plus\"); }); // Toggle plus minus icon on show hide // of collapse element $(\".collapse\").on('show.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-plus\").addClass(\"fa-minus\"); }).on('hide.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-minus\").addClass(\"fa-plus\"); }); }); </script></head> <body> <div class=\"accordion\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class=\"accordion\" id=\"accordionExample\"> <div class=\"card\"> <div class=\"card-header\" id=\"headingOne\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link\" data-toggle=\"collapse\" data-target=\"#collapseOne\"> <i class=\"fa fa-plus\"></i> GeeksforGeeks </button> </h2> </div> <div id=\"collapseOne\" class=\"collapse\" aria-labelledby=\"headingOne\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingTwo\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo\"> <i class=\"fa fa-plus\"></i> Bootstrap </button> </h2> </div> <div id=\"collapseTwo\" class=\"collapse show\" aria-labelledby=\"headingTwo\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingThree\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree\"> <i class=\"fa fa-plus\"></i> HTML </button> </h2> </div> <div id=\"collapseThree\" class=\"collapse\" aria-labelledby=\"headingThree\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <title>Bootstrap 4 Accordion </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .accordion { margin: 15px; } .accordion .fa { margin-right: 0.2rem; } </style> <script> $(document).ready(function() { // Add minus icon for collapse element which // is open by default $(\".collapse.show\").each(function() { $(this).prev(\".card-header\").find(\".fa\") .addClass(\"fa-minus\").removeClass(\"fa-plus\"); }); // Toggle plus minus icon on show hide // of collapse element $(\".collapse\").on('show.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-plus\").addClass(\"fa-minus\"); }).on('hide.bs.collapse', function() { $(this).prev(\".card-header\").find(\".fa\") .removeClass(\"fa-minus\").addClass(\"fa-plus\"); }); }); </script></head> <body> <div class=\"accordion\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div class=\"accordion\" id=\"accordionExample\"> <div class=\"card\"> <div class=\"card-header\" id=\"headingOne\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link\" data-toggle=\"collapse\" data-target=\"#collapseOne\"> <i class=\"fa fa-plus\"></i> GeeksforGeeks </button> </h2> </div> <div id=\"collapseOne\" class=\"collapse\" aria-labelledby=\"headingOne\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingTwo\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseTwo\"> <i class=\"fa fa-plus\"></i> Bootstrap </button> </h2> </div> <div id=\"collapseTwo\" class=\"collapse show\" aria-labelledby=\"headingTwo\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </p> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\" id=\"headingThree\"> <h2 class=\"mb-0\"> <button type=\"button\" class=\"btn btn-link collapsed\" data-toggle=\"collapse\" data-target=\"#collapseThree\"> <i class=\"fa fa-plus\"></i> HTML </button> </h2> </div> <div id=\"collapseThree\" class=\"collapse\" aria-labelledby=\"headingThree\" data-parent=\"#accordionExample\"> <div class=\"card-body\"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using markup language. </p> </div> </div> </div> </div> </div></body> </html>", "e": 54935, "s": 49809, "text": null }, { "code": null, "e": 54943, "s": 54935, "text": "Output:" }, { "code": null, "e": 55042, "s": 54943, "text": "Accordion with gradient background: This is a simple of accordian with the gradient color effects." }, { "code": null, "e": 58644, "s": 55042, "text": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card-header{ background-image: linear-gradient(to bottom, green, yellow); } .card-body{ background-image: linear-gradient(to right, yellow, white); } </style> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> </div> </div> </div> </div> </body> </html>", "e": 62246, "s": 58644, "text": null }, { "code": null, "e": 62254, "s": 62246, "text": "Output:" }, { "code": null, "e": 62345, "s": 62254, "text": "Accordion with the picture: In this example the accordion will conatins picture within it." }, { "code": null, "e": 66679, "s": 62345, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card{ width:600px; } .card-body{ width:400px; float: left; } .right-body{ width:100px; margin:10px; float : right; } img{ width:100px; height:100px; } </style> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> <div class=\"right-body\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png\"> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> <div class=\"right-body\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191126170417/logo6.png\"> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> <div class=\"right-body\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png\"> </div> </div> </div> </div> </div> </body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Bootstrap Collapse Demonstration</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script> <style> .card{ width:600px; } .card-body{ width:400px; float: left; } .right-body{ width:100px; margin:10px; float : right; } img{ width:100px; height:100px; } </style> <head> <body> <div class=\"container\"> <h2 style=\"padding-bottom: 15px; color:green;\"> GeeksforGeeks </h2> <p>A Computer Science Portal for Geeks</p> <div id=\"accordion\"> <div class=\"card\"> <div class=\"card-header\"> <a class=\"card-link\" data-toggle=\"collapse\" href=\"#description1\"> GeeksforGeeks </a> </div> <div id=\"description1\" class=\"collapse show\" data-parent=\"#accordion\"> <div class=\"card-body\"> GeeksforGeeks is a computer science portal. It is the best platform to lean programming. </div> <div class=\"right-body\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png\"> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description2\"> Bootstrap </a> </div> <div id=\"description2\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> Bootstrap is a free and open-source collection of tools for creating websites and web applications. </div> <div class=\"right-body\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20191126170417/logo6.png\"> </div> </div> </div> <div class=\"card\"> <div class=\"card-header\"> <a class=\"collapsed card-link\" data-toggle=\"collapse\" href=\"#description3\"> HTML </a> </div> <div id=\"description3\" class=\"collapse\" data-parent=\"#accordion\"> <div class=\"card-body\"> HTML stands for Hyper Text Markup Language. It is used to design web pages using markup language. </div> <div class=\"right-body\"> <img src=\"https://www.geeksforgeeks.org/wp-content/uploads/html-768x256.png\"> </div> </div> </div> </div> </div> </body> </html>", "e": 71005, "s": 66679, "text": null }, { "code": null, "e": 71048, "s": 71005, "text": "Output:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 71061, "s": 71048, "text": "AakashYadav4" }, { "code": null, "e": 71073, "s": 71061, "text": "Bootstrap-4" }, { "code": null, "e": 71088, "s": 71073, "text": "Bootstrap-Misc" }, { "code": null, "e": 71098, "s": 71088, "text": "Bootstrap" }, { "code": null, "e": 71115, "s": 71098, "text": "Web Technologies" }, { "code": null, "e": 71213, "s": 71115, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 71222, "s": 71213, "text": "Comments" }, { "code": null, "e": 71235, "s": 71222, "text": "Old Comments" }, { "code": null, "e": 71285, "s": 71235, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 71314, "s": 71285, "text": "Form validation using jQuery" }, { "code": null, "e": 71370, "s": 71314, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 71411, "s": 71370, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 71452, "s": 71411, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 71508, "s": 71452, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 71541, "s": 71508, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 71603, "s": 71541, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 71646, "s": 71603, "text": "How to fetch data from an API in ReactJS ?" } ]
Matplotlib savefig with a legend outside the plot
To save a file with legend outside the plot, we can take the following steps − Create x data points using numpy. Create x data points using numpy. Plot y=sin(x) curve using plot() method, with color=red, marker="v" and label y=sin(x). Plot y=sin(x) curve using plot() method, with color=red, marker="v" and label y=sin(x). Plot y=cos(x), curve using plot() method, with color=green, marker="x" and label y=cos(x). Plot y=cos(x), curve using plot() method, with color=green, marker="x" and label y=cos(x). To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location="upper center". To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location="upper center". To save the figure, use savefig() method. To save the figure, use savefig() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(-2, 2, 100) plt.plot(x, np.sin(x), c="red", marker="v", label="y=sin(x)") plt.plot(x, np.cos(x), c="green", marker="x", label="y=cos(x)") plt.legend(bbox_to_anchor=(.45, 1.15), loc="upper center") plt.savefig("legend_outside.png") When we execute this code, it will save the following plot with the name "legend_outside.png" in the current directory.
[ { "code": null, "e": 1141, "s": 1062, "text": "To save a file with legend outside the plot, we can take the following steps −" }, { "code": null, "e": 1175, "s": 1141, "text": "Create x data points using numpy." }, { "code": null, "e": 1209, "s": 1175, "text": "Create x data points using numpy." }, { "code": null, "e": 1297, "s": 1209, "text": "Plot y=sin(x) curve using plot() method, with color=red, marker=\"v\" and label y=sin(x)." }, { "code": null, "e": 1385, "s": 1297, "text": "Plot y=sin(x) curve using plot() method, with color=red, marker=\"v\" and label y=sin(x)." }, { "code": null, "e": 1476, "s": 1385, "text": "Plot y=cos(x), curve using plot() method, with color=green, marker=\"x\" and label y=cos(x)." }, { "code": null, "e": 1567, "s": 1476, "text": "Plot y=cos(x), curve using plot() method, with color=green, marker=\"x\" and label y=cos(x)." }, { "code": null, "e": 1664, "s": 1567, "text": "To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location=\"upper center\"." }, { "code": null, "e": 1761, "s": 1664, "text": "To place the legend outside the plot, use bbox_to_anchor(.45, 1.15) and location=\"upper center\"." }, { "code": null, "e": 1803, "s": 1761, "text": "To save the figure, use savefig() method." }, { "code": null, "e": 1845, "s": 1803, "text": "To save the figure, use savefig() method." }, { "code": null, "e": 2235, "s": 1845, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 100)\nplt.plot(x, np.sin(x), c=\"red\", marker=\"v\", label=\"y=sin(x)\")\nplt.plot(x, np.cos(x), c=\"green\", marker=\"x\", label=\"y=cos(x)\")\nplt.legend(bbox_to_anchor=(.45, 1.15), loc=\"upper center\")\nplt.savefig(\"legend_outside.png\")" }, { "code": null, "e": 2355, "s": 2235, "text": "When we execute this code, it will save the following plot with the name \"legend_outside.png\" in the current directory." } ]
CSS | margin-block-start Property - GeeksforGeeks
17 Feb, 2021 The margin-block-start property is used to define the logical block start margin of element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax: margin-block-start: length | auto | initial | inherit; Property values: length: It sets the fixed value defined in px, cm, pt. Negative values as mentioned earlier are allowed. 0px is the default value. auto: It is used when it is desired that the browser determines the width of the left margin. initial: It is used to set the value of the margin-left property to its default value. inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own. Below examples illustrate the margin-block-start property in CSS:Example 1: html <!DOCTYPE html><html> <head> <title>CSS | margin-block-start Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 80px; } .two { margin-block-start: 20px; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-block-start Property</b> <br><br> <div class="one">GeeksforGeeks</div> <div class="two">GFG</div> <div class="three">GeeksforGeeks</div> </center></body> </html> Output: Example 2: html <!DOCTYPE html><html> <head> <title>CSS | margin-block-start Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 80px; } .two { margin-block-start: auto; writing-mode: vertical-lr; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-block-start Property</b> <br><br> <div class="one">GeeksforGeeks</div> <div class="two">GFG</div> <div class="three">GeeksforGeeks</div> </center></body> </html> Output: Supported Browsers: The browser supported by margin-block-start property are listed below: Google Chrome Internet Explorer Mozilla Firefox arorakashish0911 CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24524, "s": 24496, "text": "\n17 Feb, 2021" }, { "code": null, "e": 24741, "s": 24524, "text": "The margin-block-start property is used to define the logical block start margin of element. This property helps to place margin depending on the element’s writing mode, directionality, and text orientation.Syntax: " }, { "code": null, "e": 24796, "s": 24741, "text": "margin-block-start: length | auto | initial | inherit;" }, { "code": null, "e": 24815, "s": 24796, "text": "Property values: " }, { "code": null, "e": 24946, "s": 24815, "text": "length: It sets the fixed value defined in px, cm, pt. Negative values as mentioned earlier are allowed. 0px is the default value." }, { "code": null, "e": 25040, "s": 24946, "text": "auto: It is used when it is desired that the browser determines the width of the left margin." }, { "code": null, "e": 25127, "s": 25040, "text": "initial: It is used to set the value of the margin-left property to its default value." }, { "code": null, "e": 25242, "s": 25127, "text": "inherit: It is used when it is desired that the element inherit the margin-left property of its parent as its own." }, { "code": null, "e": 25320, "s": 25242, "text": "Below examples illustrate the margin-block-start property in CSS:Example 1: " }, { "code": null, "e": 25325, "s": 25320, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | margin-block-start Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 80px; } .two { margin-block-start: 20px; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-block-start Property</b> <br><br> <div class=\"one\">GeeksforGeeks</div> <div class=\"two\">GFG</div> <div class=\"three\">GeeksforGeeks</div> </center></body> </html>", "e": 25966, "s": 25325, "text": null }, { "code": null, "e": 25976, "s": 25966, "text": "Output: " }, { "code": null, "e": 25989, "s": 25976, "text": "Example 2: " }, { "code": null, "e": 25994, "s": 25989, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | margin-block-start Property</title> <style> h1 { color: green; } div { background-color: yellow; width: 110px; height: 80px; } .two { margin-block-start: auto; writing-mode: vertical-lr; background-color: purple; } </style></head> <body> <center> <h1>Geeksforgeeks</h1> <b>CSS | margin-block-start Property</b> <br><br> <div class=\"one\">GeeksforGeeks</div> <div class=\"two\">GFG</div> <div class=\"three\">GeeksforGeeks</div> </center></body> </html> ", "e": 26688, "s": 25994, "text": null }, { "code": null, "e": 26698, "s": 26688, "text": "Output: " }, { "code": null, "e": 26791, "s": 26698, "text": "Supported Browsers: The browser supported by margin-block-start property are listed below: " }, { "code": null, "e": 26805, "s": 26791, "text": "Google Chrome" }, { "code": null, "e": 26823, "s": 26805, "text": "Internet Explorer" }, { "code": null, "e": 26839, "s": 26823, "text": "Mozilla Firefox" }, { "code": null, "e": 26858, "s": 26841, "text": "arorakashish0911" }, { "code": null, "e": 26873, "s": 26858, "text": "CSS-Properties" }, { "code": null, "e": 26877, "s": 26873, "text": "CSS" }, { "code": null, "e": 26894, "s": 26877, "text": "Web Technologies" }, { "code": null, "e": 26992, "s": 26894, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27050, "s": 26992, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27087, "s": 27050, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27151, "s": 27087, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27192, "s": 27151, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27229, "s": 27192, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27271, "s": 27229, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27304, "s": 27271, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27347, "s": 27304, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27392, "s": 27347, "text": "Convert a string to an integer in JavaScript" } ]
Odd numbers in N-th row of Pascal's Triangle - GeeksforGeeks
26 May, 2021 Given N, the row number of Pascal’s triangle(row starting from 0). Find the count of odd numbers in the N-th row of Pascal’s Triangle.Prerequisite: Pascal’s Triangle | Count number of 1’s in binary representation of N Examples: Input : 11 Output : 8 Input : 20 Output : 4 Approach: It appears the answer is always a power of 2. In fact, the following theorem exists: THEOREM: The number of odd entries in row N of Pascal’s Triangle is 2 raised to the number of 1’s in the binary expansion of N. Example: Since 83 = 64 + 16 + 2 + 1 has binary expansion (1010011), then row 83 has pow(2, 4) = 16 odd numbers. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP code to find the count of odd numbers// in n-th row of Pascal's Triangle#include <bits/stdc++.h> using namespace std ; /* Function to get no of set bits in binary representation of positive integer n */int countSetBits(int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} int countOfOddsPascal(int n){ // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the count. return pow(2, c);} // Driver codeint main(){ int n = 20; cout << countOfOddsPascal(n) ; return 0;} // Java code to find the count of odd// numbers in n-th row of Pascal's// Triangleimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { long count = 0; while (n > 0) { count += n & 1; n >>= 1; } return (int)count; } static int countOfOddsPascal(int n) { // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return (int)Math.pow(2, c); } // Driver code public static void main (String[] args) { int n = 20; System.out.println( countOfOddsPascal(n)); }} // This code is contributed by anuj_67. # Python code to find the count of# odd numbers in n-th row of# Pascal's Triangle # Function to get no of set# bits in binary representation# of positive integer ndef countSetBits(n): count =0 while n: count += n & 1 n >>= 1 return count def countOfOddPascal(n): # Count number of 1's in binary # representation of n. c = countSetBits(n) # Number of odd numbers in n-th # row is 2 raised to power the count. return pow(2, c) # Driver Programn = 20print(countOfOddPascal(n)) # This code is contributed by Shrikant13 // C# code to find the count of odd numbers// in n-th row of Pascal's Triangleusing System; class GFG { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } static int countOfOddsPascal(int n) { // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return (int)Math.Pow(2, c); } // Driver code public static void Main () { int n = 20; Console.WriteLine( countOfOddsPascal(n)) ; }} // This code is contributed by anuj_67. <?php// PHP code to find the// count of odd numbers// in n-th row of Pascal's// Triangle /* Function to get no of set bits in binary representation of positive integer n */function countSetBits($n){ $count = 0; while ($n) { $count += $n & 1; $n >>= 1; } return $count;} function countOfOddsPascal($n){ // Count number of 1's in binary // representation of n. $c = countSetBits($n); // Number of odd numbers in n-th // row is 2 raised to power the count. return pow(2, $c);} // Driver code $n = 20; echo countOfOddsPascal($n) ; // This code is contributed by mits.?> <script> // Javascript code to find the count of odd numbers // in n-th row of Pascal's Triangle /* Function to get no of set bits in binary representation of positive integer n */ function countSetBits(n) { let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } function countOfOddsPascal(n) { // Count number of 1's in binary // representation of n. let c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return Math.pow(2, c); } let n = 20; document.write(countOfOddsPascal(n)) ; </script> 4 Time Complexity: O(L), where L is the length of a binary representation of a given N. shrikanth13 Mithun Kumar vt_m suresh07 binomial coefficient Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Find the size of Largest Subset with positive Bitwise AND Check whether bitwise AND of a number with any subset of an array is zero or not Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Swap two nibbles in a byte Swap bits in a given number Check for Integer Overflow Reverse actual bits of the given number Find one extra character in a string
[ { "code": null, "e": 26279, "s": 26251, "text": "\n26 May, 2021" }, { "code": null, "e": 26497, "s": 26279, "text": "Given N, the row number of Pascal’s triangle(row starting from 0). Find the count of odd numbers in the N-th row of Pascal’s Triangle.Prerequisite: Pascal’s Triangle | Count number of 1’s in binary representation of N" }, { "code": null, "e": 26509, "s": 26497, "text": "Examples: " }, { "code": null, "e": 26555, "s": 26509, "text": "Input : 11\nOutput : 8\n\nInput : 20\nOutput : 4 " }, { "code": null, "e": 26890, "s": 26555, "text": "Approach: It appears the answer is always a power of 2. In fact, the following theorem exists: THEOREM: The number of odd entries in row N of Pascal’s Triangle is 2 raised to the number of 1’s in the binary expansion of N. Example: Since 83 = 64 + 16 + 2 + 1 has binary expansion (1010011), then row 83 has pow(2, 4) = 16 odd numbers." }, { "code": null, "e": 26942, "s": 26890, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26946, "s": 26942, "text": "C++" }, { "code": null, "e": 26951, "s": 26946, "text": "Java" }, { "code": null, "e": 26959, "s": 26951, "text": "Python3" }, { "code": null, "e": 26962, "s": 26959, "text": "C#" }, { "code": null, "e": 26966, "s": 26962, "text": "PHP" }, { "code": null, "e": 26977, "s": 26966, "text": "Javascript" }, { "code": " // CPP code to find the count of odd numbers// in n-th row of Pascal's Triangle#include <bits/stdc++.h> using namespace std ; /* Function to get no of set bits in binary representation of positive integer n */int countSetBits(int n){ unsigned int count = 0; while (n) { count += n & 1; n >>= 1; } return count;} int countOfOddsPascal(int n){ // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the count. return pow(2, c);} // Driver codeint main(){ int n = 20; cout << countOfOddsPascal(n) ; return 0;}", "e": 27654, "s": 26977, "text": null }, { "code": "// Java code to find the count of odd// numbers in n-th row of Pascal's// Triangleimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { long count = 0; while (n > 0) { count += n & 1; n >>= 1; } return (int)count; } static int countOfOddsPascal(int n) { // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return (int)Math.pow(2, c); } // Driver code public static void main (String[] args) { int n = 20; System.out.println( countOfOddsPascal(n)); }} // This code is contributed by anuj_67.", "e": 28564, "s": 27654, "text": null }, { "code": "# Python code to find the count of# odd numbers in n-th row of# Pascal's Triangle # Function to get no of set# bits in binary representation# of positive integer ndef countSetBits(n): count =0 while n: count += n & 1 n >>= 1 return count def countOfOddPascal(n): # Count number of 1's in binary # representation of n. c = countSetBits(n) # Number of odd numbers in n-th # row is 2 raised to power the count. return pow(2, c) # Driver Programn = 20print(countOfOddPascal(n)) # This code is contributed by Shrikant13", "e": 29131, "s": 28564, "text": null }, { "code": "// C# code to find the count of odd numbers// in n-th row of Pascal's Triangleusing System; class GFG { /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } static int countOfOddsPascal(int n) { // Count number of 1's in binary // representation of n. int c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return (int)Math.Pow(2, c); } // Driver code public static void Main () { int n = 20; Console.WriteLine( countOfOddsPascal(n)) ; }} // This code is contributed by anuj_67.", "e": 30001, "s": 29131, "text": null }, { "code": "<?php// PHP code to find the// count of odd numbers// in n-th row of Pascal's// Triangle /* Function to get no of set bits in binary representation of positive integer n */function countSetBits($n){ $count = 0; while ($n) { $count += $n & 1; $n >>= 1; } return $count;} function countOfOddsPascal($n){ // Count number of 1's in binary // representation of n. $c = countSetBits($n); // Number of odd numbers in n-th // row is 2 raised to power the count. return pow(2, $c);} // Driver code $n = 20; echo countOfOddsPascal($n) ; // This code is contributed by mits.?>", "e": 30643, "s": 30001, "text": null }, { "code": "<script> // Javascript code to find the count of odd numbers // in n-th row of Pascal's Triangle /* Function to get no of set bits in binary representation of positive integer n */ function countSetBits(n) { let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } function countOfOddsPascal(n) { // Count number of 1's in binary // representation of n. let c = countSetBits(n); // Number of odd numbers in n-th // row is 2 raised to power the // count. return Math.pow(2, c); } let n = 20; document.write(countOfOddsPascal(n)) ; </script>", "e": 31391, "s": 30643, "text": null }, { "code": null, "e": 31393, "s": 31391, "text": "4" }, { "code": null, "e": 31483, "s": 31395, "text": "Time Complexity: O(L), where L is the length of a binary representation of a given N. " }, { "code": null, "e": 31495, "s": 31483, "text": "shrikanth13" }, { "code": null, "e": 31508, "s": 31495, "text": "Mithun Kumar" }, { "code": null, "e": 31513, "s": 31508, "text": "vt_m" }, { "code": null, "e": 31522, "s": 31513, "text": "suresh07" }, { "code": null, "e": 31543, "s": 31522, "text": "binomial coefficient" }, { "code": null, "e": 31553, "s": 31543, "text": "Bit Magic" }, { "code": null, "e": 31563, "s": 31553, "text": "Bit Magic" }, { "code": null, "e": 31661, "s": 31563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31712, "s": 31661, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31770, "s": 31712, "text": "Find the size of Largest Subset with positive Bitwise AND" }, { "code": null, "e": 31851, "s": 31770, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 31915, "s": 31851, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 31969, "s": 31915, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 31996, "s": 31969, "text": "Swap two nibbles in a byte" }, { "code": null, "e": 32024, "s": 31996, "text": "Swap bits in a given number" }, { "code": null, "e": 32051, "s": 32024, "text": "Check for Integer Overflow" }, { "code": null, "e": 32091, "s": 32051, "text": "Reverse actual bits of the given number" } ]
Check if directory contains files using python - GeeksforGeeks
29 Dec, 2020 Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(<directory path>) Returns: A list of files present in the directory, empty list if the directory is empty Now by calling listdir() method, we can get a list of all files present in the directory. To check the emptiness of the directory we should check the emptiness of the returned list. We have many ways to do that, let us check them one by one. By comparing the returned list with a hardcoded empty listAn empty list can be written as []. So we can compare the returned list’s equalness with [].# Python program to check# if a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. By comparing length of the returned list with 0We can get length of a list by using len() method of Python. If the length of the returned list is equal to zero then the directory is empty otherwise not.# Python program to check if# a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. By comparing the boolean value of the listIn the above method, we used explicit comparison of the length of the list. Now we are heading with a more Pythonic way using truth value testing. An empty list is evaluated as False in Python.# Python program to check if# a directory is empty import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the boolean value of listif not os.listdir(directoryPath): print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. By comparing the returned list with a hardcoded empty listAn empty list can be written as []. So we can compare the returned list’s equalness with [].# Python program to check# if a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. # Python program to check# if a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print("No files found in the directory.") else: print("Some files found in the directory.") Output: Some files found in the directory. By comparing length of the returned list with 0We can get length of a list by using len() method of Python. If the length of the returned list is equal to zero then the directory is empty otherwise not.# Python program to check if# a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. # Python program to check if# a directory contains file import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print("No files found in the directory.") else: print("Some files found in the directory.") Output: Some files found in the directory. By comparing the boolean value of the listIn the above method, we used explicit comparison of the length of the list. Now we are heading with a more Pythonic way using truth value testing. An empty list is evaluated as False in Python.# Python program to check if# a directory is empty import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the boolean value of listif not os.listdir(directoryPath): print("No files found in the directory.") else: print("Some files found in the directory.")Output:Some files found in the directory. # Python program to check if# a directory is empty import os # path of the directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil" # Checking the boolean value of listif not os.listdir(directoryPath): print("No files found in the directory.") else: print("Some files found in the directory.") Output: Some files found in the directory. # Python program to check if# the directory is empty import os # Function for checking if the directory# containes file or notdef isEmpty(directoryPath): # Checking if the directory exists or not if os.path.exists(directoryPath): # Checking if the directory is empty or not if len(os.listdir(directoryPath)) == 0: return "No files found in the directory." else: return "Some files found in the directory." else: return "Directory does not exist !" # Driver's code # Valid directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil"print("Valid path:", isEmpty(directoryPath)) # Invalid directorydirectoryPath = "D:/Pycharm projects/GeeksforGeeks/Nikhil/GeeksforGeeks"print("Invalid path:", isEmpty(directoryPath)) Output: Valid path: Some files found in the directory. Invalid path: Directory does not exist ! SriHarshaBammidi Python os-module-programs python-os-module Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2020" }, { "code": null, "e": 25817, "s": 25537, "text": "Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 25854, "s": 25817, "text": "Syntax: os.listdir(<directory path>)" }, { "code": null, "e": 25942, "s": 25854, "text": "Returns: A list of files present in the directory, empty list if the directory is empty" }, { "code": null, "e": 26184, "s": 25942, "text": "Now by calling listdir() method, we can get a list of all files present in the directory. To check the emptiness of the directory we should check the emptiness of the returned list. We have many ways to do that, let us check them one by one." }, { "code": null, "e": 27894, "s": 26184, "text": "By comparing the returned list with a hardcoded empty listAn empty list can be written as []. So we can compare the returned list’s equalness with [].# Python program to check# if a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\nBy comparing length of the returned list with 0We can get length of a list by using len() method of Python. If the length of the returned list is equal to zero then the directory is empty otherwise not.# Python program to check if# a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\nBy comparing the boolean value of the listIn the above method, we used explicit comparison of the length of the list. Now we are heading with a more Pythonic way using truth value testing. An empty list is evaluated as False in Python.# Python program to check if# a directory is empty import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the boolean value of listif not os.listdir(directoryPath): print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\n" }, { "code": null, "e": 28427, "s": 27894, "text": "By comparing the returned list with a hardcoded empty listAn empty list can be written as []. So we can compare the returned list’s equalness with [].# Python program to check# if a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\n" }, { "code": "# Python program to check# if a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Comparing the returned list to empty listif os.listdir(directoryPath) == []: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")", "e": 28768, "s": 28427, "text": null }, { "code": null, "e": 28776, "s": 28768, "text": "Output:" }, { "code": null, "e": 28812, "s": 28776, "text": "Some files found in the directory.\n" }, { "code": null, "e": 29387, "s": 28812, "text": "By comparing length of the returned list with 0We can get length of a list by using len() method of Python. If the length of the returned list is equal to zero then the directory is empty otherwise not.# Python program to check if# a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\n" }, { "code": "# Python program to check if# a directory contains file import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the length of listif len(os.listdir(directoryPath)) == 0: print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")", "e": 29718, "s": 29387, "text": null }, { "code": null, "e": 29726, "s": 29718, "text": "Output:" }, { "code": null, "e": 29762, "s": 29726, "text": "Some files found in the directory.\n" }, { "code": null, "e": 30366, "s": 29762, "text": "By comparing the boolean value of the listIn the above method, we used explicit comparison of the length of the list. Now we are heading with a more Pythonic way using truth value testing. An empty list is evaluated as False in Python.# Python program to check if# a directory is empty import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the boolean value of listif not os.listdir(directoryPath): print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")Output:Some files found in the directory.\n" }, { "code": "# Python program to check if# a directory is empty import os # path of the directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\" # Checking the boolean value of listif not os.listdir(directoryPath): print(\"No files found in the directory.\") else: print(\"Some files found in the directory.\")", "e": 30693, "s": 30366, "text": null }, { "code": null, "e": 30701, "s": 30693, "text": "Output:" }, { "code": null, "e": 30737, "s": 30701, "text": "Some files found in the directory.\n" }, { "code": "# Python program to check if# the directory is empty import os # Function for checking if the directory# containes file or notdef isEmpty(directoryPath): # Checking if the directory exists or not if os.path.exists(directoryPath): # Checking if the directory is empty or not if len(os.listdir(directoryPath)) == 0: return \"No files found in the directory.\" else: return \"Some files found in the directory.\" else: return \"Directory does not exist !\" # Driver's code # Valid directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil\"print(\"Valid path:\", isEmpty(directoryPath)) # Invalid directorydirectoryPath = \"D:/Pycharm projects/GeeksforGeeks/Nikhil/GeeksforGeeks\"print(\"Invalid path:\", isEmpty(directoryPath))", "e": 31530, "s": 30737, "text": null }, { "code": null, "e": 31538, "s": 31530, "text": "Output:" }, { "code": null, "e": 31627, "s": 31538, "text": "Valid path: Some files found in the directory.\nInvalid path: Directory does not exist !\n" }, { "code": null, "e": 31644, "s": 31627, "text": "SriHarshaBammidi" }, { "code": null, "e": 31670, "s": 31644, "text": "Python os-module-programs" }, { "code": null, "e": 31687, "s": 31670, "text": "python-os-module" }, { "code": null, "e": 31694, "s": 31687, "text": "Python" }, { "code": null, "e": 31713, "s": 31694, "text": "Technical Scripter" }, { "code": null, "e": 31811, "s": 31713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31843, "s": 31811, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31885, "s": 31843, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31927, "s": 31885, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31983, "s": 31927, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32010, "s": 31983, "text": "Python Classes and Objects" }, { "code": null, "e": 32049, "s": 32010, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32080, "s": 32049, "text": "Python | os.path.join() method" }, { "code": null, "e": 32102, "s": 32080, "text": "Defaultdict in Python" }, { "code": null, "e": 32131, "s": 32102, "text": "Create a directory in Python" } ]
Pig Game Design using JavaScript - GeeksforGeeks
18 Mar, 2021 In this article, we will be explaining the steps and various logic required in making of the famous Pig Game, which is a virtual dice game. About Game: In this game, User Interface (UI) contains user/player that can do three things, they are as follows: There will be two players in this game. At the start of the game Player 1 will be the CurrentPlayer and Player 2 will be the in-active one. Roll the dice: The current player has to roll the dice and then a random number will be generated. If current player gets any number other than 1 on the dice then that number will be added to the current score (initially the current score will be 0) and then the new score will be displayed under Current Score section. Note: If the current player gets 1 on the dice then the players will be switched i.e. the current player will become in-active and vice-versa.Hold: If the current player clicks on HOLD, then the Current Score will be added to the Total Score. When the active player clicks the Hold button then the total score is evaluated. If the Total Score >= 100 then the current player wins else the players are switched.Reset: All the scores are set to 0 and Player 1 is set as the starting player (current player). Roll the dice: The current player has to roll the dice and then a random number will be generated. If current player gets any number other than 1 on the dice then that number will be added to the current score (initially the current score will be 0) and then the new score will be displayed under Current Score section. Note: If the current player gets 1 on the dice then the players will be switched i.e. the current player will become in-active and vice-versa. Hold: If the current player clicks on HOLD, then the Current Score will be added to the Total Score. When the active player clicks the Hold button then the total score is evaluated. If the Total Score >= 100 then the current player wins else the players are switched. Reset: All the scores are set to 0 and Player 1 is set as the starting player (current player). Making of Game: Being a game rendered by the web browser, it is built by the help of HTML, CSS (for the Front-end) and JavaScript (for the Back-end). The main logic of the game lies in the JS file whereas the appearance and the User Interface is rendered by HTML and CSS. In this project, there are basically four types of files: HTML File (index.html) CSS File (style.css) JavaScript File (script.js file) Images (dice.png file) We will analyze all these files and thus make you understand their work/contribution in this game. So, first let’s start with index.html file: HTML File: Index.html file is the file that makes the web browsers understand and thus interprets what type of document we are making. It stands for Hyper Text Markup Language, our web browsers read this file and understand its component via the V8 Engine (which parses the code in a language so that the browser can understand it). Below is the HTML code for this game: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="style.css" /> <title>Pig Game Design using JavaScript</title></head> <body> <div class="container"> <section class="player player--0 player--active"> <div class="tscore"> <h2 class="name" id="name--0"> Total Score<br> <span class="pl">Player 1</span> </h2> <p class="score" id="score--0">43</p> </div> <div class="current"> <p class="current-label">Current Score</p> <p class="current-score" id="current--0">0</p> </div> </section> <section class="player player--1"> <div class="tscore"> <h2 class="name" id="name--1"> Total Score<br> <span class="pl">Player 2</span> </h2> <p class="score" id="score--1">24</p> </div> <div class="current"> <p class="current-label">Current Score</p> <p class="current-score" id="current--1">0</p> </div> </section> <img src="dice-5.png" alt="Playing dice" class="dice" /> <button class="btn btn--new">Start Game</button> <button class="btn btn--roll">Roll dice</button> <button class="btn btn--hold">Hold</button> </div> <script src="gfg.js"></script></body> </html> In the above code, we have used various classes (for eg: btn btn–roll, rte), these will be used for the styling purpose in the CSS file, and will discuss them under the CSS files. CSS File: In order to format and style the markup created by HTML, we need Cascading Style Sheets so that the markup (code) looks way better. Below is the CSS code for the game is given below. Before diving in the code, just have a quick look at which classes and ids are for what purpose: For overall HTML page and elements: * will affect the every element and tag in the markup. We have used 2 more tags to provide some particular styling which are html and body tag’s styling.Layout elements: Defined main tag & player class styling there. We have defined position attribute for main tag and set its property to relative.Self Made Classes: General styling needed to make the page more appealing.Absolute Positioned Classes: I have set the position attribute of btn and other classes and set its value to absolute as we have to make sure that the buttons and other elements are always at the right place in the page. Absolute position will make the arrangement of that particular element according to the element which is positioned relative (in this case, it is the main tag). For overall HTML page and elements: * will affect the every element and tag in the markup. We have used 2 more tags to provide some particular styling which are html and body tag’s styling. Layout elements: Defined main tag & player class styling there. We have defined position attribute for main tag and set its property to relative. Self Made Classes: General styling needed to make the page more appealing. Absolute Positioned Classes: I have set the position attribute of btn and other classes and set its value to absolute as we have to make sure that the buttons and other elements are always at the right place in the page. Absolute position will make the arrangement of that particular element according to the element which is positioned relative (in this case, it is the main tag). CSS * { margin: 0; padding: 0;} body { height: 100vh; display: flex; justify-content: center; align-items: center;} .container { position: relative; width: 80%; height: 90%; background-color: lightgreen; overflow: hidden; display: flex;} .player { flex: 50%; padding: 150px; display: flex; flex-direction: column; align-items: center; transition: all 0.75s;} .name { position: relative; font-weight: bold; font-size: 38px; text-align: center;} .pl { font-size: 24px;} .tscore { background-color: #fff; border-radius: 9px; width: 65%; padding: 2rem; text-align: center; transition: all 0.75s;} .score { font-size: 38px; font-weight: bold; margin-bottom: auto; padding-top: 10px;} .player--active { background-color: green;} .player--active .current { opacity: 1;} .current { margin-top: 10rem; background-color: #fff; border-radius: 9px; width: 65%; padding: 2rem; text-align: center; transition: all 0.75s;} .current-label { text-transform: uppercase; margin-bottom: 1rem; font-size: 1.7rem; color: #ddd;} .current-score { font-size: 3.5rem;} .btn { position: absolute; left: 50%; transform: translateX(-50%); color: rgb(7, 124, 69); border: none; font-size: 30px; cursor: pointer; font-weight: bold; background-color: rgba(255, 255, 255, 0.6); backdrop-filter: blur(10px); padding: 10px 30px; border-radius: 10px;} .btn--new { top: 4rem;} .btn--roll { top: 39.3rem;} .btn--hold { top: 46.1rem;} .dice { position: absolute; left: 50%; top: 24rem; transform: translateX(-50%);} .player--winner { background-color: #003612;} .player--winner .name { font-weight: 700; color: #c7365f;} .hidden { display: none;} In the HTML code, we have provided names of various classes. In this file, we have provided their different functionalities. The CSS file plays an important role in making a webpage or a game look good (only in the case of web browsers). Till now, we have made the UI of the game perfectly, now comes the trickier part. So let’s dive into the Game Logic... JavaScript File: There are some JavaScript variables, we can use two type of variables i.e. let and constant. One can modify the variables declared with let, while the variables declared with constant can’t be changed. In the JavaScript file, we are basically doing the DOM Manipulations (everything in JavaScript is a type of Object, so we term the UI as the Document Object Model). So document.querySelector() is a way of selecting elements from the DOM. In order to understand the work-flow of the logic, we have to first understand the concept of Event Listeners. Event Listeners are the functions that performs an action based on certain events. They wait for the specific event to happen. We have a total of 03 event listeners for this game: btnRoll, btnHold, btnNew. We will understand functionalities of all these event listeners: Note: Before heading to the event handlers section, we must declare some variables in the file so that we can use them later in our game logic. Javascript 'use strict'; // Selecting elementsconst player0El = document.querySelector('.player--0');const player1El = document.querySelector('.player--1');const score0El = document.querySelector('#score--0');const score1El = document.getElementById('score--1');const current0El = document.getElementById('current--0');const current1El = document.getElementById('current--1'); const diceEl = document.querySelector('.dice');const btnNew = document.querySelector('.btn--new');const btnRoll = document.querySelector('.btn--roll');const btnHold = document.querySelector('.btn--hold'); let scores, currentScore, activePlayer, playing; At the very beginning of the JavaScript File, there is a line ‘use strict’. The purpose of “use strict” is to indicate that the code should be executed in “strict mode”. All modern browsers support “use strict” except Internet Explorer 9 and lower. Now lets start to see the code for each of the 3 event handlers. 1. btnRoll Event Handler: Javascript // Rolling dice functionalitybtnRoll.addEventListener('click', function () { if (playing) { // 1. Generating a random dice roll const dice = Math.trunc(Math.random() * 6) + 1; // 2. Display dice diceEl.classList.remove('hidden'); diceEl.src = `dice-${dice}.png`; // 3. Check for rolled 1 if (dice !== 1) { // Add dice to current score currentScore += dice; document.getElementById( `current--${activePlayer}` ).textContent = currentScore; } else { // Switch to next player switchPlayer(); } }}); This event handler is in action whenever the player clicks on Roll button (that is why we have used the click event there). Then there is a callback function which starts with an if-else block. As we have declared the variable playing = true, so the if block of this event handler will be true and thus the code of if block will be executed. Following are the steps ahead: Step1: After the player hits the roll dice button, this event handler produces a random number using the Math.trunc() function. We have used Math.trunc() function because this function returns the integer portion of the randomly generated function and have added a 1 to it because the random() function can generate any number starting from 0 to 1 but in our case, we only need numbers from 1 to 6. <br>Understanding the dice variable: The dice variable will store the random generated number. Say the Math.random() function generates number 0.02. According to the code, first 0.02 will be multiplied by 6. So variable dice will now have a value of 0.12. Then the Math.trunc() function will come into play and will make the dice variable 0. Now 1 will be addded to the variable which will make the dice = 1 (That is what we need as a number for our dice)Step2: Now we have got the score for the dice, we have to display the dice corresponding to the number of dice. (In the CSS file, we have made a class named as hidden which will make the dice hidden initially at the start of the game) But as now we have a dice number to be displayed in the form of dice image, we have to remove the hidden class. This is achieved by the line diceE1.classList.remove(‘hidden’) and then the correct image of dice is rendered to the UI. Step3. Now as per the game rules, we have to check the number on the dice. So, if the dice number is not 1 then current score is updated. If the dice number is 1, then switchPlayer() gets invoked. Step1: After the player hits the roll dice button, this event handler produces a random number using the Math.trunc() function. We have used Math.trunc() function because this function returns the integer portion of the randomly generated function and have added a 1 to it because the random() function can generate any number starting from 0 to 1 but in our case, we only need numbers from 1 to 6. <br>Understanding the dice variable: The dice variable will store the random generated number. Say the Math.random() function generates number 0.02. According to the code, first 0.02 will be multiplied by 6. So variable dice will now have a value of 0.12. Then the Math.trunc() function will come into play and will make the dice variable 0. Now 1 will be addded to the variable which will make the dice = 1 (That is what we need as a number for our dice) Step2: Now we have got the score for the dice, we have to display the dice corresponding to the number of dice. (In the CSS file, we have made a class named as hidden which will make the dice hidden initially at the start of the game) But as now we have a dice number to be displayed in the form of dice image, we have to remove the hidden class. This is achieved by the line diceE1.classList.remove(‘hidden’) and then the correct image of dice is rendered to the UI. Step3. Now as per the game rules, we have to check the number on the dice. So, if the dice number is not 1 then current score is updated. If the dice number is 1, then switchPlayer() gets invoked. Javascript const switchPlayer = function () { document.getElementById(`current--${activePlayer}`).textContent = 0; currentScore = 0; activePlayer = activePlayer === 0 ? 1 : 0; player0El.classList.toggle('player--active'); player1El.classList.toggle('player--active');}; According to the rules: “If the player rolls out a 1, then he losts all of his current score”. The same functionality is being achieved by this function. activePlayer = activePlayer === 0 ? 1 : 0 {This is a ternary operator in which we are saying that if the activeplayer is 0 then make it 1 and if it is make then turn it to 0. 2. btnHold Event Handler Javascript btnHold.addEventListener('click', function () { if (playing) { // 1. Add current score to active player's score scores[activePlayer] += currentScore; // scores[1] = scores[1] + currentScore document.getElementById(`score--${activePlayer}`) .textContent = scores[activePlayer]; // 2. Check if player's score is >= 100 if (scores[activePlayer] >= 100) { // Finish the game playing = false; diceEl.classList.add('hidden'); document .querySelector(`.player--${activePlayer}`) .classList.add('player--winner'); document .querySelector(`.player--${activePlayer}`) .classList.remove('player--active'); } else { // Switch to the next player switchPlayer(); } }}); This event handler fires off whenever a player hits the HOLD button. Following are the steps involved in this handler: Step1: As soon as the player hits hold, the current score gets added to the overall score of that player.Step2: Evaluation of the overall scores is done after that step. If overall score is found to be greater than 100, then the game finishes and then the class of player-winner (which make the background-color: black and changes the color and font-weight) and removes the class of active-player. Step1: As soon as the player hits hold, the current score gets added to the overall score of that player. Step2: Evaluation of the overall scores is done after that step. If overall score is found to be greater than 100, then the game finishes and then the class of player-winner (which make the background-color: black and changes the color and font-weight) and removes the class of active-player. 3. btnNew Event Handler: btnNew.addEventListener(‘click’,init): Whenever a new game is initialized, this event handler fires off. It only does initialize the Init() function. Init() kinds of reset the game to the start, that is it does the following things: Makes the scores of both players 0. Makes the Player 1 as the active/current player. Hides the dice by the hidden class. Removes the player–winner class from both players Adds the player–active class to Player 1 Javascript // Starting conditionsconst init = function () { scores = [0, 0]; currentScore = 0; activePlayer = 0; playing = true; score0El.textContent = 0; score1El.textContent = 0; current0El.textContent = 0; current1El.textContent = 0; diceEl.classList.add('hidden'); player0El.classList.remove('player--winner'); player1El.classList.remove('player--winner'); player0El.classList.add('player--active'); player1El.classList.remove('player--active');};init(); Note: init() function is initialized at the time of loading the game also. Output: Reference of Diced Images: dice-1.png dice-2.png dice-3.png dice-4.png dice-5.png dice-6.png CSS-Misc HTML-Misc JavaScript-Misc Technical Scripter 2020 CSS HTML JavaScript Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26645, "s": 26617, "text": "\n18 Mar, 2021" }, { "code": null, "e": 26786, "s": 26645, "text": "In this article, we will be explaining the steps and various logic required in making of the famous Pig Game, which is a virtual dice game. " }, { "code": null, "e": 26900, "s": 26786, "text": "About Game: In this game, User Interface (UI) contains user/player that can do three things, they are as follows:" }, { "code": null, "e": 27040, "s": 26900, "text": "There will be two players in this game. At the start of the game Player 1 will be the CurrentPlayer and Player 2 will be the in-active one." }, { "code": null, "e": 27866, "s": 27040, "text": "Roll the dice: The current player has to roll the dice and then a random number will be generated. If current player gets any number other than 1 on the dice then that number will be added to the current score (initially the current score will be 0) and then the new score will be displayed under Current Score section. Note: If the current player gets 1 on the dice then the players will be switched i.e. the current player will become in-active and vice-versa.Hold: If the current player clicks on HOLD, then the Current Score will be added to the Total Score. When the active player clicks the Hold button then the total score is evaluated. If the Total Score >= 100 then the current player wins else the players are switched.Reset: All the scores are set to 0 and Player 1 is set as the starting player (current player)." }, { "code": null, "e": 28330, "s": 27866, "text": "Roll the dice: The current player has to roll the dice and then a random number will be generated. If current player gets any number other than 1 on the dice then that number will be added to the current score (initially the current score will be 0) and then the new score will be displayed under Current Score section. Note: If the current player gets 1 on the dice then the players will be switched i.e. the current player will become in-active and vice-versa." }, { "code": null, "e": 28598, "s": 28330, "text": "Hold: If the current player clicks on HOLD, then the Current Score will be added to the Total Score. When the active player clicks the Hold button then the total score is evaluated. If the Total Score >= 100 then the current player wins else the players are switched." }, { "code": null, "e": 28694, "s": 28598, "text": "Reset: All the scores are set to 0 and Player 1 is set as the starting player (current player)." }, { "code": null, "e": 29024, "s": 28694, "text": "Making of Game: Being a game rendered by the web browser, it is built by the help of HTML, CSS (for the Front-end) and JavaScript (for the Back-end). The main logic of the game lies in the JS file whereas the appearance and the User Interface is rendered by HTML and CSS. In this project, there are basically four types of files:" }, { "code": null, "e": 29047, "s": 29024, "text": "HTML File (index.html)" }, { "code": null, "e": 29068, "s": 29047, "text": "CSS File (style.css)" }, { "code": null, "e": 29101, "s": 29068, "text": "JavaScript File (script.js file)" }, { "code": null, "e": 29124, "s": 29101, "text": "Images (dice.png file)" }, { "code": null, "e": 29267, "s": 29124, "text": "We will analyze all these files and thus make you understand their work/contribution in this game. So, first let’s start with index.html file:" }, { "code": null, "e": 29638, "s": 29267, "text": "HTML File: Index.html file is the file that makes the web browsers understand and thus interprets what type of document we are making. It stands for Hyper Text Markup Language, our web browsers read this file and understand its component via the V8 Engine (which parses the code in a language so that the browser can understand it). Below is the HTML code for this game:" }, { "code": null, "e": 29643, "s": 29638, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <link rel=\"stylesheet\" href=\"style.css\" /> <title>Pig Game Design using JavaScript</title></head> <body> <div class=\"container\"> <section class=\"player player--0 player--active\"> <div class=\"tscore\"> <h2 class=\"name\" id=\"name--0\"> Total Score<br> <span class=\"pl\">Player 1</span> </h2> <p class=\"score\" id=\"score--0\">43</p> </div> <div class=\"current\"> <p class=\"current-label\">Current Score</p> <p class=\"current-score\" id=\"current--0\">0</p> </div> </section> <section class=\"player player--1\"> <div class=\"tscore\"> <h2 class=\"name\" id=\"name--1\"> Total Score<br> <span class=\"pl\">Player 2</span> </h2> <p class=\"score\" id=\"score--1\">24</p> </div> <div class=\"current\"> <p class=\"current-label\">Current Score</p> <p class=\"current-score\" id=\"current--1\">0</p> </div> </section> <img src=\"dice-5.png\" alt=\"Playing dice\" class=\"dice\" /> <button class=\"btn btn--new\">Start Game</button> <button class=\"btn btn--roll\">Roll dice</button> <button class=\"btn btn--hold\">Hold</button> </div> <script src=\"gfg.js\"></script></body> </html>", "e": 31301, "s": 29643, "text": null }, { "code": null, "e": 31481, "s": 31301, "text": "In the above code, we have used various classes (for eg: btn btn–roll, rte), these will be used for the styling purpose in the CSS file, and will discuss them under the CSS files." }, { "code": null, "e": 31771, "s": 31481, "text": "CSS File: In order to format and style the markup created by HTML, we need Cascading Style Sheets so that the markup (code) looks way better. Below is the CSS code for the game is given below. Before diving in the code, just have a quick look at which classes and ids are for what purpose:" }, { "code": null, "e": 32561, "s": 31771, "text": "For overall HTML page and elements: * will affect the every element and tag in the markup. We have used 2 more tags to provide some particular styling which are html and body tag’s styling.Layout elements: Defined main tag & player class styling there. We have defined position attribute for main tag and set its property to relative.Self Made Classes: General styling needed to make the page more appealing.Absolute Positioned Classes: I have set the position attribute of btn and other classes and set its value to absolute as we have to make sure that the buttons and other elements are always at the right place in the page. Absolute position will make the arrangement of that particular element according to the element which is positioned relative (in this case, it is the main tag)." }, { "code": null, "e": 32751, "s": 32561, "text": "For overall HTML page and elements: * will affect the every element and tag in the markup. We have used 2 more tags to provide some particular styling which are html and body tag’s styling." }, { "code": null, "e": 32897, "s": 32751, "text": "Layout elements: Defined main tag & player class styling there. We have defined position attribute for main tag and set its property to relative." }, { "code": null, "e": 32972, "s": 32897, "text": "Self Made Classes: General styling needed to make the page more appealing." }, { "code": null, "e": 33354, "s": 32972, "text": "Absolute Positioned Classes: I have set the position attribute of btn and other classes and set its value to absolute as we have to make sure that the buttons and other elements are always at the right place in the page. Absolute position will make the arrangement of that particular element according to the element which is positioned relative (in this case, it is the main tag)." }, { "code": null, "e": 33358, "s": 33354, "text": "CSS" }, { "code": "* { margin: 0; padding: 0;} body { height: 100vh; display: flex; justify-content: center; align-items: center;} .container { position: relative; width: 80%; height: 90%; background-color: lightgreen; overflow: hidden; display: flex;} .player { flex: 50%; padding: 150px; display: flex; flex-direction: column; align-items: center; transition: all 0.75s;} .name { position: relative; font-weight: bold; font-size: 38px; text-align: center;} .pl { font-size: 24px;} .tscore { background-color: #fff; border-radius: 9px; width: 65%; padding: 2rem; text-align: center; transition: all 0.75s;} .score { font-size: 38px; font-weight: bold; margin-bottom: auto; padding-top: 10px;} .player--active { background-color: green;} .player--active .current { opacity: 1;} .current { margin-top: 10rem; background-color: #fff; border-radius: 9px; width: 65%; padding: 2rem; text-align: center; transition: all 0.75s;} .current-label { text-transform: uppercase; margin-bottom: 1rem; font-size: 1.7rem; color: #ddd;} .current-score { font-size: 3.5rem;} .btn { position: absolute; left: 50%; transform: translateX(-50%); color: rgb(7, 124, 69); border: none; font-size: 30px; cursor: pointer; font-weight: bold; background-color: rgba(255, 255, 255, 0.6); backdrop-filter: blur(10px); padding: 10px 30px; border-radius: 10px;} .btn--new { top: 4rem;} .btn--roll { top: 39.3rem;} .btn--hold { top: 46.1rem;} .dice { position: absolute; left: 50%; top: 24rem; transform: translateX(-50%);} .player--winner { background-color: #003612;} .player--winner .name { font-weight: 700; color: #c7365f;} .hidden { display: none;}", "e": 35192, "s": 33358, "text": null }, { "code": null, "e": 35430, "s": 35192, "text": "In the HTML code, we have provided names of various classes. In this file, we have provided their different functionalities. The CSS file plays an important role in making a webpage or a game look good (only in the case of web browsers)." }, { "code": null, "e": 35549, "s": 35430, "text": "Till now, we have made the UI of the game perfectly, now comes the trickier part. So let’s dive into the Game Logic..." }, { "code": null, "e": 36007, "s": 35549, "text": "JavaScript File: There are some JavaScript variables, we can use two type of variables i.e. let and constant. One can modify the variables declared with let, while the variables declared with constant can’t be changed. In the JavaScript file, we are basically doing the DOM Manipulations (everything in JavaScript is a type of Object, so we term the UI as the Document Object Model). So document.querySelector() is a way of selecting elements from the DOM. " }, { "code": null, "e": 36391, "s": 36007, "text": "In order to understand the work-flow of the logic, we have to first understand the concept of Event Listeners. Event Listeners are the functions that performs an action based on certain events. They wait for the specific event to happen. We have a total of 03 event listeners for this game: btnRoll, btnHold, btnNew. We will understand functionalities of all these event listeners:" }, { "code": null, "e": 36535, "s": 36391, "text": "Note: Before heading to the event handlers section, we must declare some variables in the file so that we can use them later in our game logic." }, { "code": null, "e": 36546, "s": 36535, "text": "Javascript" }, { "code": "'use strict'; // Selecting elementsconst player0El = document.querySelector('.player--0');const player1El = document.querySelector('.player--1');const score0El = document.querySelector('#score--0');const score1El = document.getElementById('score--1');const current0El = document.getElementById('current--0');const current1El = document.getElementById('current--1'); const diceEl = document.querySelector('.dice');const btnNew = document.querySelector('.btn--new');const btnRoll = document.querySelector('.btn--roll');const btnHold = document.querySelector('.btn--hold'); let scores, currentScore, activePlayer, playing;", "e": 37169, "s": 36546, "text": null }, { "code": null, "e": 37420, "s": 37169, "text": "At the very beginning of the JavaScript File, there is a line ‘use strict’. The purpose of “use strict” is to indicate that the code should be executed in “strict mode”. All modern browsers support “use strict” except Internet Explorer 9 and lower. " }, { "code": null, "e": 37485, "s": 37420, "text": "Now lets start to see the code for each of the 3 event handlers." }, { "code": null, "e": 37511, "s": 37485, "text": "1. btnRoll Event Handler:" }, { "code": null, "e": 37522, "s": 37511, "text": "Javascript" }, { "code": "// Rolling dice functionalitybtnRoll.addEventListener('click', function () { if (playing) { // 1. Generating a random dice roll const dice = Math.trunc(Math.random() * 6) + 1; // 2. Display dice diceEl.classList.remove('hidden'); diceEl.src = `dice-${dice}.png`; // 3. Check for rolled 1 if (dice !== 1) { // Add dice to current score currentScore += dice; document.getElementById( `current--${activePlayer}` ).textContent = currentScore; } else { // Switch to next player switchPlayer(); } }});", "e": 38104, "s": 37522, "text": null }, { "code": null, "e": 38477, "s": 38104, "text": "This event handler is in action whenever the player clicks on Roll button (that is why we have used the click event there). Then there is a callback function which starts with an if-else block. As we have declared the variable playing = true, so the if block of this event handler will be true and thus the code of if block will be executed. Following are the steps ahead:" }, { "code": null, "e": 39997, "s": 38477, "text": "Step1: After the player hits the roll dice button, this event handler produces a random number using the Math.trunc() function. We have used Math.trunc() function because this function returns the integer portion of the randomly generated function and have added a 1 to it because the random() function can generate any number starting from 0 to 1 but in our case, we only need numbers from 1 to 6. <br>Understanding the dice variable: The dice variable will store the random generated number. Say the Math.random() function generates number 0.02. According to the code, first 0.02 will be multiplied by 6. So variable dice will now have a value of 0.12. Then the Math.trunc() function will come into play and will make the dice variable 0. Now 1 will be addded to the variable which will make the dice = 1 (That is what we need as a number for our dice)Step2: Now we have got the score for the dice, we have to display the dice corresponding to the number of dice. (In the CSS file, we have made a class named as hidden which will make the dice hidden initially at the start of the game) But as now we have a dice number to be displayed in the form of dice image, we have to remove the hidden class. This is achieved by the line diceE1.classList.remove(‘hidden’) and then the correct image of dice is rendered to the UI. Step3. Now as per the game rules, we have to check the number on the dice. So, if the dice number is not 1 then current score is updated. If the dice number is 1, then switchPlayer() gets invoked. " }, { "code": null, "e": 40852, "s": 39997, "text": "Step1: After the player hits the roll dice button, this event handler produces a random number using the Math.trunc() function. We have used Math.trunc() function because this function returns the integer portion of the randomly generated function and have added a 1 to it because the random() function can generate any number starting from 0 to 1 but in our case, we only need numbers from 1 to 6. <br>Understanding the dice variable: The dice variable will store the random generated number. Say the Math.random() function generates number 0.02. According to the code, first 0.02 will be multiplied by 6. So variable dice will now have a value of 0.12. Then the Math.trunc() function will come into play and will make the dice variable 0. Now 1 will be addded to the variable which will make the dice = 1 (That is what we need as a number for our dice)" }, { "code": null, "e": 41321, "s": 40852, "text": "Step2: Now we have got the score for the dice, we have to display the dice corresponding to the number of dice. (In the CSS file, we have made a class named as hidden which will make the dice hidden initially at the start of the game) But as now we have a dice number to be displayed in the form of dice image, we have to remove the hidden class. This is achieved by the line diceE1.classList.remove(‘hidden’) and then the correct image of dice is rendered to the UI. " }, { "code": null, "e": 41519, "s": 41321, "text": "Step3. Now as per the game rules, we have to check the number on the dice. So, if the dice number is not 1 then current score is updated. If the dice number is 1, then switchPlayer() gets invoked. " }, { "code": null, "e": 41530, "s": 41519, "text": "Javascript" }, { "code": "const switchPlayer = function () { document.getElementById(`current--${activePlayer}`).textContent = 0; currentScore = 0; activePlayer = activePlayer === 0 ? 1 : 0; player0El.classList.toggle('player--active'); player1El.classList.toggle('player--active');};", "e": 41794, "s": 41530, "text": null }, { "code": null, "e": 41948, "s": 41794, "text": "According to the rules: “If the player rolls out a 1, then he losts all of his current score”. The same functionality is being achieved by this function." }, { "code": null, "e": 42124, "s": 41948, "text": "activePlayer = activePlayer === 0 ? 1 : 0 {This is a ternary operator in which we are saying that if the activeplayer is 0 then make it 1 and if it is make then turn it to 0." }, { "code": null, "e": 42149, "s": 42124, "text": "2. btnHold Event Handler" }, { "code": null, "e": 42160, "s": 42149, "text": "Javascript" }, { "code": "btnHold.addEventListener('click', function () { if (playing) { // 1. Add current score to active player's score scores[activePlayer] += currentScore; // scores[1] = scores[1] + currentScore document.getElementById(`score--${activePlayer}`) .textContent = scores[activePlayer]; // 2. Check if player's score is >= 100 if (scores[activePlayer] >= 100) { // Finish the game playing = false; diceEl.classList.add('hidden'); document .querySelector(`.player--${activePlayer}`) .classList.add('player--winner'); document .querySelector(`.player--${activePlayer}`) .classList.remove('player--active'); } else { // Switch to the next player switchPlayer(); } }});", "e": 42932, "s": 42160, "text": null }, { "code": null, "e": 43051, "s": 42932, "text": "This event handler fires off whenever a player hits the HOLD button. Following are the steps involved in this handler:" }, { "code": null, "e": 43449, "s": 43051, "text": "Step1: As soon as the player hits hold, the current score gets added to the overall score of that player.Step2: Evaluation of the overall scores is done after that step. If overall score is found to be greater than 100, then the game finishes and then the class of player-winner (which make the background-color: black and changes the color and font-weight) and removes the class of active-player." }, { "code": null, "e": 43555, "s": 43449, "text": "Step1: As soon as the player hits hold, the current score gets added to the overall score of that player." }, { "code": null, "e": 43848, "s": 43555, "text": "Step2: Evaluation of the overall scores is done after that step. If overall score is found to be greater than 100, then the game finishes and then the class of player-winner (which make the background-color: black and changes the color and font-weight) and removes the class of active-player." }, { "code": null, "e": 43873, "s": 43848, "text": "3. btnNew Event Handler:" }, { "code": null, "e": 44106, "s": 43873, "text": "btnNew.addEventListener(‘click’,init): Whenever a new game is initialized, this event handler fires off. It only does initialize the Init() function. Init() kinds of reset the game to the start, that is it does the following things:" }, { "code": null, "e": 44142, "s": 44106, "text": "Makes the scores of both players 0." }, { "code": null, "e": 44191, "s": 44142, "text": "Makes the Player 1 as the active/current player." }, { "code": null, "e": 44227, "s": 44191, "text": "Hides the dice by the hidden class." }, { "code": null, "e": 44277, "s": 44227, "text": "Removes the player–winner class from both players" }, { "code": null, "e": 44318, "s": 44277, "text": "Adds the player–active class to Player 1" }, { "code": null, "e": 44329, "s": 44318, "text": "Javascript" }, { "code": "// Starting conditionsconst init = function () { scores = [0, 0]; currentScore = 0; activePlayer = 0; playing = true; score0El.textContent = 0; score1El.textContent = 0; current0El.textContent = 0; current1El.textContent = 0; diceEl.classList.add('hidden'); player0El.classList.remove('player--winner'); player1El.classList.remove('player--winner'); player0El.classList.add('player--active'); player1El.classList.remove('player--active');};init();", "e": 44794, "s": 44329, "text": null }, { "code": null, "e": 44870, "s": 44794, "text": "Note: init() function is initialized at the time of loading the game also. " }, { "code": null, "e": 44878, "s": 44870, "text": "Output:" }, { "code": null, "e": 44905, "s": 44878, "text": "Reference of Diced Images:" }, { "code": null, "e": 44916, "s": 44905, "text": "dice-1.png" }, { "code": null, "e": 44927, "s": 44916, "text": "dice-2.png" }, { "code": null, "e": 44938, "s": 44927, "text": "dice-3.png" }, { "code": null, "e": 44949, "s": 44938, "text": "dice-4.png" }, { "code": null, "e": 44960, "s": 44949, "text": "dice-5.png" }, { "code": null, "e": 44971, "s": 44960, "text": "dice-6.png" }, { "code": null, "e": 44980, "s": 44971, "text": "CSS-Misc" }, { "code": null, "e": 44990, "s": 44980, "text": "HTML-Misc" }, { "code": null, "e": 45006, "s": 44990, "text": "JavaScript-Misc" }, { "code": null, "e": 45030, "s": 45006, "text": "Technical Scripter 2020" }, { "code": null, "e": 45034, "s": 45030, "text": "CSS" }, { "code": null, "e": 45039, "s": 45034, "text": "HTML" }, { "code": null, "e": 45050, "s": 45039, "text": "JavaScript" }, { "code": null, "e": 45069, "s": 45050, "text": "Technical Scripter" }, { "code": null, "e": 45086, "s": 45069, "text": "Web Technologies" }, { "code": null, "e": 45113, "s": 45086, "text": "Web technologies Questions" }, { "code": null, "e": 45118, "s": 45113, "text": "HTML" }, { "code": null, "e": 45216, "s": 45118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45255, "s": 45216, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 45292, "s": 45255, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 45321, "s": 45292, "text": "Form validation using jQuery" }, { "code": null, "e": 45363, "s": 45321, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 45398, "s": 45363, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 45458, "s": 45398, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 45511, "s": 45458, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 45572, "s": 45511, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 45596, "s": 45572, "text": "REST API (Introduction)" } ]
Technical Challenges of Mobile Computing - GeeksforGeeks
06 Jan, 2020 Mobile Computing is defined as a computing environment which is mobile and moves along with the user. There are various number of challenges that affected mobile computing and it has to overcome them. Some of the major technical challenges faced by mobile computing are: 1. Mobility 2. Wireless Medium 3. Portability These are explained as following below: 1. Mobility:It is the most important aspect of mobile computing, but it has to face the certain challenges which are : Auto configuration of the system, as the environment of the system is developing continuously. Hence for every change, it has to configure itself to the new situation. Location management is also a big objection in mobility. To manage the location, following tasks are to be performed regularly over a fixed period of time.Track user’s call.Update user’s position and data. Track user’s call. Update user’s position and data. To maintain the heterogenity is also a big task as the system is keep moving in a large variation of situations Range of spectrum. Verification of security. 2. Wireless Medium:The transmission medium in mobile computing is wireless, therefore the following points are considered: Various interferences occurs in the mobile computing by the different elements in the environment. Accuracy and quantity of bandwidth should be sufficient. Network cost is feasible. 3. Portability:This means that the communication device moves, for eg. mobile phones. The following mobile constraints are to be considered as the devices are also mobile: Minimum number of resources are used. Security is very less, as security risks include the processing of fake transactions, unauthorized access of data and program files, and the physical theft or damage of the device. Restrictions of the battery. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Congestion Control in Computer Networks Routing Information Protocol (RIP) Wireless Sensor Network (WSN) Architecture of Internet of Things (IoT)
[ { "code": null, "e": 25755, "s": 25727, "text": "\n06 Jan, 2020" }, { "code": null, "e": 26026, "s": 25755, "text": "Mobile Computing is defined as a computing environment which is mobile and moves along with the user. There are various number of challenges that affected mobile computing and it has to overcome them. Some of the major technical challenges faced by mobile computing are:" }, { "code": null, "e": 26073, "s": 26026, "text": "1. Mobility\n2. Wireless Medium\n3. Portability " }, { "code": null, "e": 26113, "s": 26073, "text": "These are explained as following below:" }, { "code": null, "e": 26232, "s": 26113, "text": "1. Mobility:It is the most important aspect of mobile computing, but it has to face the certain challenges which are :" }, { "code": null, "e": 26400, "s": 26232, "text": "Auto configuration of the system, as the environment of the system is developing continuously. Hence for every change, it has to configure itself to the new situation." }, { "code": null, "e": 26606, "s": 26400, "text": "Location management is also a big objection in mobility. To manage the location, following tasks are to be performed regularly over a fixed period of time.Track user’s call.Update user’s position and data." }, { "code": null, "e": 26625, "s": 26606, "text": "Track user’s call." }, { "code": null, "e": 26658, "s": 26625, "text": "Update user’s position and data." }, { "code": null, "e": 26770, "s": 26658, "text": "To maintain the heterogenity is also a big task as the system is keep moving in a large variation of situations" }, { "code": null, "e": 26789, "s": 26770, "text": "Range of spectrum." }, { "code": null, "e": 26815, "s": 26789, "text": "Verification of security." }, { "code": null, "e": 26938, "s": 26815, "text": "2. Wireless Medium:The transmission medium in mobile computing is wireless, therefore the following points are considered:" }, { "code": null, "e": 27037, "s": 26938, "text": "Various interferences occurs in the mobile computing by the different elements in the environment." }, { "code": null, "e": 27094, "s": 27037, "text": "Accuracy and quantity of bandwidth should be sufficient." }, { "code": null, "e": 27120, "s": 27094, "text": "Network cost is feasible." }, { "code": null, "e": 27292, "s": 27120, "text": "3. Portability:This means that the communication device moves, for eg. mobile phones. The following mobile constraints are to be considered as the devices are also mobile:" }, { "code": null, "e": 27330, "s": 27292, "text": "Minimum number of resources are used." }, { "code": null, "e": 27511, "s": 27330, "text": "Security is very less, as security risks include the processing of fake transactions, unauthorized access of data and program files, and the physical theft or damage of the device." }, { "code": null, "e": 27540, "s": 27511, "text": "Restrictions of the battery." }, { "code": null, "e": 27558, "s": 27540, "text": "Computer Networks" }, { "code": null, "e": 27576, "s": 27558, "text": "Computer Networks" }, { "code": null, "e": 27674, "s": 27576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27709, "s": 27674, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 27742, "s": 27709, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 27780, "s": 27742, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 27806, "s": 27780, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 27833, "s": 27806, "text": "Cryptography and its Types" }, { "code": null, "e": 27879, "s": 27833, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 27919, "s": 27879, "text": "Congestion Control in Computer Networks" }, { "code": null, "e": 27954, "s": 27919, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 27984, "s": 27954, "text": "Wireless Sensor Network (WSN)" } ]
Exception handling in JSP - GeeksforGeeks
28 Sep, 2021 Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage attributes of page directive By <error-page> element in web.xml file Handling Exception using page directive attributes The page directive in JSP provides two attributes to be used in exception handling. They’re: errorPage: Used to site which page to be displayed when exception occurred.Syntax : <%@page errorPage="url of the error page"%> isErrorPage: Used to mark a page as an error page where exceptions are displayed. Syntax : <%@page isErrorPage="true"%> In order to handle exceptions using the aforementioned page directives, it is important to have a jsp page to execute the normal code, which is prone to exceptions. Also, a separate error page is to be created, which will display the exception. In case the exception occurs on the page with the exception prone code, the control will be navigated to the error page which will display the exception. The following is an example illustrating exception handling using page directives: index.html HTML <html><head><body><form action="a.jsp"> Number1:<input type="text" name="first" >Number2:<input type="text" name="second" ><input type="submit" value="divide"> </form> </body></html> A.jsp Java // JSP code to divide two numbers<% @page errorPage = "error.jsp" %> < % String num1 = request.getParameter("first");String num2 = request.getParameter("second"); // extracting numbers from requestint x = Integer.parseInt(num1);int y = Integer.parseInt(num2);int z = x / y; // dividing the numbersout.print("division of numbers is: " + z); // result % > error.jsp Java // JSP code for error page, which displays the exception<% @page isErrorPage = "true" %> <h1> Exception caught</ h1> The exception is : <%= exception %> // displaying the exception Output: index.html error.jsp Handling Exceptions Using error-page Element En web.xml File This is another way of specifying the error page for each element, but instead of using the errorPage directive, the error page for each page can be specified in the web.xml file, using the <error-page> element. The syntax is as follows: HTML <web-app> <error-page> <exception-type>Type of Exception</exception-type> <location>Error page url</location> </error-page> </web-app> The following example illustrates using this technique to handle exceptions: index.html HTML <html><head><body><form action="a.jsp"> Number1:<input type="text" name="first" >Number2:<input type="text" name="second" ><input type="submit" value="divide"> </form> </body></html> a.jsp Java // JSP code to divide two numbers< % String num1 = request.getParameter("first");String num2 = request.getParameter("second");// extracting the numbersint x = Integer.parseInt(num1);int y = Integer.parseInt(num2);int z = x / y; // dividingout.print("division of numbers is: " + z); // result % > error.jsp Java // JSP code for error page, which displays the exception<%@ page isErrorPage="true" %> <h1>Exception caught</h1> // displaying the exceptionThe exception is: <%= exception %> web.xml HTML <web-app> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page> </web-app> The output, in this case, is similar as in the previous one. Akanksha_Rai varshagumber28 Java-JSP Java Web Technologies 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 Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25227, "s": 25199, "text": "\n28 Sep, 2021" }, { "code": null, "e": 25438, "s": 25227, "text": "Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages." }, { "code": null, "e": 25499, "s": 25438, "text": "There are two ways of handling exceptions in JSP. They are: " }, { "code": null, "e": 25557, "s": 25499, "text": "By errorPage and isErrorPage attributes of page directive" }, { "code": null, "e": 25597, "s": 25557, "text": "By <error-page> element in web.xml file" }, { "code": null, "e": 25648, "s": 25597, "text": "Handling Exception using page directive attributes" }, { "code": null, "e": 25743, "s": 25648, "text": "The page directive in JSP provides two attributes to be used in exception handling. They’re: " }, { "code": null, "e": 25827, "s": 25743, "text": "errorPage: Used to site which page to be displayed when exception occurred.Syntax :" }, { "code": null, "e": 25872, "s": 25827, "text": " <%@page errorPage=\"url of the error page\"%>" }, { "code": null, "e": 25963, "s": 25872, "text": "isErrorPage: Used to mark a page as an error page where exceptions are displayed. Syntax :" }, { "code": null, "e": 25993, "s": 25963, "text": " <%@page isErrorPage=\"true\"%>" }, { "code": null, "e": 26392, "s": 25993, "text": "In order to handle exceptions using the aforementioned page directives, it is important to have a jsp page to execute the normal code, which is prone to exceptions. Also, a separate error page is to be created, which will display the exception. In case the exception occurs on the page with the exception prone code, the control will be navigated to the error page which will display the exception." }, { "code": null, "e": 26475, "s": 26392, "text": "The following is an example illustrating exception handling using page directives:" }, { "code": null, "e": 26488, "s": 26475, "text": "index.html " }, { "code": null, "e": 26493, "s": 26488, "text": "HTML" }, { "code": "<html><head><body><form action=\"a.jsp\"> Number1:<input type=\"text\" name=\"first\" >Number2:<input type=\"text\" name=\"second\" ><input type=\"submit\" value=\"divide\"> </form> </body></html>", "e": 26676, "s": 26493, "text": null }, { "code": null, "e": 26683, "s": 26676, "text": "A.jsp " }, { "code": null, "e": 26688, "s": 26683, "text": "Java" }, { "code": "// JSP code to divide two numbers<% @page errorPage = \"error.jsp\" %> < % String num1 = request.getParameter(\"first\");String num2 = request.getParameter(\"second\"); // extracting numbers from requestint x = Integer.parseInt(num1);int y = Integer.parseInt(num2);int z = x / y; // dividing the numbersout.print(\"division of numbers is: \" + z); // result % >", "e": 27087, "s": 26688, "text": null }, { "code": null, "e": 27098, "s": 27087, "text": "error.jsp " }, { "code": null, "e": 27103, "s": 27098, "text": "Java" }, { "code": "// JSP code for error page, which displays the exception<% @page isErrorPage = \"true\" %> <h1> Exception caught</ h1> The exception is : <%= exception %> // displaying the exception", "e": 27296, "s": 27103, "text": null }, { "code": null, "e": 27316, "s": 27296, "text": "Output: index.html " }, { "code": null, "e": 27327, "s": 27316, "text": "error.jsp " }, { "code": null, "e": 27388, "s": 27327, "text": "Handling Exceptions Using error-page Element En web.xml File" }, { "code": null, "e": 27626, "s": 27388, "text": "This is another way of specifying the error page for each element, but instead of using the errorPage directive, the error page for each page can be specified in the web.xml file, using the <error-page> element. The syntax is as follows:" }, { "code": null, "e": 27631, "s": 27626, "text": "HTML" }, { "code": "<web-app> <error-page> <exception-type>Type of Exception</exception-type> <location>Error page url</location> </error-page> </web-app> ", "e": 27781, "s": 27631, "text": null }, { "code": null, "e": 27858, "s": 27781, "text": "The following example illustrates using this technique to handle exceptions:" }, { "code": null, "e": 27870, "s": 27858, "text": "index.html " }, { "code": null, "e": 27875, "s": 27870, "text": "HTML" }, { "code": "<html><head><body><form action=\"a.jsp\"> Number1:<input type=\"text\" name=\"first\" >Number2:<input type=\"text\" name=\"second\" ><input type=\"submit\" value=\"divide\"> </form> </body></html>", "e": 28058, "s": 27875, "text": null }, { "code": null, "e": 28065, "s": 28058, "text": "a.jsp " }, { "code": null, "e": 28070, "s": 28065, "text": "Java" }, { "code": "// JSP code to divide two numbers< % String num1 = request.getParameter(\"first\");String num2 = request.getParameter(\"second\");// extracting the numbersint x = Integer.parseInt(num1);int y = Integer.parseInt(num2);int z = x / y; // dividingout.print(\"division of numbers is: \" + z); // result % >", "e": 28377, "s": 28070, "text": null }, { "code": null, "e": 28388, "s": 28377, "text": "error.jsp " }, { "code": null, "e": 28393, "s": 28388, "text": "Java" }, { "code": "// JSP code for error page, which displays the exception<%@ page isErrorPage=\"true\" %> <h1>Exception caught</h1> // displaying the exceptionThe exception is: <%= exception %>", "e": 28574, "s": 28393, "text": null }, { "code": null, "e": 28583, "s": 28574, "text": "web.xml " }, { "code": null, "e": 28588, "s": 28583, "text": "HTML" }, { "code": "<web-app> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page> </web-app> ", "e": 28736, "s": 28588, "text": null }, { "code": null, "e": 28798, "s": 28736, "text": "The output, in this case, is similar as in the previous one. " }, { "code": null, "e": 28811, "s": 28798, "text": "Akanksha_Rai" }, { "code": null, "e": 28826, "s": 28811, "text": "varshagumber28" }, { "code": null, "e": 28835, "s": 28826, "text": "Java-JSP" }, { "code": null, "e": 28840, "s": 28835, "text": "Java" }, { "code": null, "e": 28857, "s": 28840, "text": "Web Technologies" }, { "code": null, "e": 28862, "s": 28857, "text": "Java" }, { "code": null, "e": 28960, "s": 28862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28975, "s": 28960, "text": "Stream In Java" }, { "code": null, "e": 28996, "s": 28975, "text": "Constructors in Java" }, { "code": null, "e": 29015, "s": 28996, "text": "Exceptions in Java" }, { "code": null, "e": 29045, "s": 29015, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29091, "s": 29045, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29131, "s": 29091, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29164, "s": 29131, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29209, "s": 29164, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29252, "s": 29209, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript String replaceAll() Method - GeeksforGeeks
07 Oct, 2021 Below is an example of the String replaceAll() Method. Javascript <script>function gfg() { let string = "Geeks or Geeks"; newString = string.replaceAll("or", "for"); document.write(newString);}gfg();</script> Output: Geeks for Geeks The replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression. The original string is left unchanged after this operation. Syntax: const newString = originalString.replaceAll(regexp | substr , newSubstr | function) Parameters: This method accepts certain parameters defined below: regexp: It is the regular expression whose matches are replaced with the newSubstr or the value returned by the specified function. substr: It defines the sub strings which are to replace with newSubstr or the value returned by the specified function. newSubstr: It is the sub string that replaces all the matches of the string specified by the substr or the regular expression. function: It is the function that is invoked to replace the matches with the regexp or substr. Javascript <script>function GFG() { let string = "Hello, what are you doing?"; newString = string.replaceAll("Hello", "Hi"); document.write(newString);}GFG();</script> Hi, what are you doing? Javascript <script>function GFG() { const regexp = /coffee/ig; let string = "Lets, have coffee today!"; newString = string.replaceAll(regexp, "tea"); document.write(newString);}GFG();</script> Output: Lets, have tea today! Supported Browser: Chrome 85 and above Edge 85 and above Firefox 77 and above Opera 71 and above Safari 13.1 and above ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26600, "s": 26545, "text": "Below is an example of the String replaceAll() Method." }, { "code": null, "e": 26611, "s": 26600, "text": "Javascript" }, { "code": "<script>function gfg() { let string = \"Geeks or Geeks\"; newString = string.replaceAll(\"or\", \"for\"); document.write(newString);}gfg();</script>", "e": 26763, "s": 26611, "text": null }, { "code": null, "e": 26771, "s": 26763, "text": "Output:" }, { "code": null, "e": 26787, "s": 26771, "text": "Geeks for Geeks" }, { "code": null, "e": 26925, "s": 26787, "text": "The replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression." }, { "code": null, "e": 26985, "s": 26925, "text": "The original string is left unchanged after this operation." }, { "code": null, "e": 26993, "s": 26985, "text": "Syntax:" }, { "code": null, "e": 27077, "s": 26993, "text": "const newString = originalString.replaceAll(regexp | substr , newSubstr | function)" }, { "code": null, "e": 27145, "s": 27079, "text": "Parameters: This method accepts certain parameters defined below:" }, { "code": null, "e": 27279, "s": 27147, "text": "regexp: It is the regular expression whose matches are replaced with the newSubstr or the value returned by the specified function." }, { "code": null, "e": 27399, "s": 27279, "text": "substr: It defines the sub strings which are to replace with newSubstr or the value returned by the specified function." }, { "code": null, "e": 27526, "s": 27399, "text": "newSubstr: It is the sub string that replaces all the matches of the string specified by the substr or the regular expression." }, { "code": null, "e": 27621, "s": 27526, "text": "function: It is the function that is invoked to replace the matches with the regexp or substr." }, { "code": null, "e": 27634, "s": 27623, "text": "Javascript" }, { "code": "<script>function GFG() { let string = \"Hello, what are you doing?\"; newString = string.replaceAll(\"Hello\", \"Hi\"); document.write(newString);}GFG();</script>", "e": 27800, "s": 27634, "text": null }, { "code": null, "e": 27827, "s": 27803, "text": "Hi, what are you doing?" }, { "code": null, "e": 27840, "s": 27829, "text": "Javascript" }, { "code": "<script>function GFG() { const regexp = /coffee/ig; let string = \"Lets, have coffee today!\"; newString = string.replaceAll(regexp, \"tea\"); document.write(newString);}GFG();</script>", "e": 28034, "s": 27840, "text": null }, { "code": null, "e": 28043, "s": 28034, "text": " Output:" }, { "code": null, "e": 28065, "s": 28043, "text": "Lets, have tea today!" }, { "code": null, "e": 28086, "s": 28067, "text": "Supported Browser:" }, { "code": null, "e": 28106, "s": 28086, "text": "Chrome 85 and above" }, { "code": null, "e": 28124, "s": 28106, "text": "Edge 85 and above" }, { "code": null, "e": 28145, "s": 28124, "text": "Firefox 77 and above" }, { "code": null, "e": 28164, "s": 28145, "text": "Opera 71 and above" }, { "code": null, "e": 28186, "s": 28164, "text": "Safari 13.1 and above" }, { "code": null, "e": 28198, "s": 28186, "text": "ysachin2314" }, { "code": null, "e": 28217, "s": 28198, "text": "JavaScript-Methods" }, { "code": null, "e": 28235, "s": 28217, "text": "javascript-string" }, { "code": null, "e": 28246, "s": 28235, "text": "JavaScript" }, { "code": null, "e": 28263, "s": 28246, "text": "Web Technologies" }, { "code": null, "e": 28361, "s": 28263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28401, "s": 28361, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28462, "s": 28401, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28503, "s": 28462, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28525, "s": 28503, "text": "JavaScript | Promises" }, { "code": null, "e": 28579, "s": 28525, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28619, "s": 28579, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28652, "s": 28619, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28695, "s": 28652, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28745, "s": 28695, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Find Minimum Number of Edges to Cut to Make the Graph Disconnected - GeeksforGeeks
24 Jun, 2021 Given a connected graph, the task is to find the minimum number of edges to cut/remove to make the given graph disconnected. A graph is disconnected if there exists at least two vertices of the graph that are not connected by a path. Examples: Input: Output: Minimum Number of Edges to Remove = 2 Approach: The approach to this problem is to find the number of paths in the edge disjoint set of paths from a start vertex to an end vertex in the graph. Edge-disjoint set of paths is a set of paths having no common edge between any two paths. Pick one node as start node and another node as end node.Start BFS from the start node and check if a path exists from start node to end node.If yes, then remove all the edges from that path and run BFS again.Repeat step 2 and 3 until there’s no path exists from start node to end node.Return the number of times a path is deleted. Pick one node as start node and another node as end node. Start BFS from the start node and check if a path exists from start node to end node. If yes, then remove all the edges from that path and run BFS again. Repeat step 2 and 3 until there’s no path exists from start node to end node. Return the number of times a path is deleted. Explanation with example: Code: Java // Java Program to Find// Minimum Number of Edges// to Cut to make the// Graph Disconnected import java.util.*; public class GFG { // Function to find the min number of edges public static int minEdgesRemoval(int[][] edges, int n) { // Initialize adjacency list for Graph Map<Integer, List<Integer> > graph = new HashMap<Integer, List<Integer> >(); // Initializing starting and ending vertex int start = edges[0][0]; int end = edges[0][1]; // Create adjacency list of the graph for (int i = 0; i < n; i++) { int n1 = edges[i][0]; int n2 = edges[i][1]; List<Integer> li; // Add edges node 1 if (graph.containsKey(n1)) { li = graph.get(n1); } else { li = new ArrayList<Integer>(); } li.add(n2); graph.put(n1, li); // Add edges node 2 if (graph.containsKey(n2)) { li = graph.get(n2); } else { li = new ArrayList<Integer>(); } li.add(n1); graph.put(n2, li); } // Variable to count the number of paths getting // deleted int deleteEdgeCount = 0; while (true) { // bfsTraversalPath is the BFS path from start // to end node It is a map of parent vertex and // child vertex Map<Integer, Integer> bfsTraversalPath = bfs(graph, start); // If end is present on the path from start node // then delete that path and increment // deleteEdgeCount if (bfsTraversalPath.containsKey(end)) { deleteEdgeCount++; int parent = bfsTraversalPath.get(end); int currEnd = end; // Delete all the edges in the current path while (parent != -1) { deleteEdge(graph, parent, currEnd); deleteEdge(graph, currEnd, parent); currEnd = parent; parent = bfsTraversalPath.get(currEnd); } } // If end is not present in the path // then we have a disconnected graph. else { break; } } return deleteEdgeCount; } // Function to delete/remove an edge private static void deleteEdge(Map<Integer, List<Integer> > graph, Integer start, Integer end) { List<Integer> list = graph.get(start); list.remove(end); } // Function for BFS Path private static Map<Integer, Integer> bfs(Map<Integer, List<Integer> > graph, int start) { // Map for BFS Path Map<Integer, Integer> bfsTraversalPath = new HashMap<Integer, Integer>(); // Array for marking visited vertex List<Integer> visited = new ArrayList<Integer>(); // Array for BFS List<Integer> queue = new ArrayList<Integer>(); int qStartIndex = 0; bfsTraversalPath.put(start, -1); queue.add(start); while (qStartIndex < queue.size()) { int curr = queue.get(qStartIndex++); visited.add(curr); for (int k : graph.get(curr)) { if (!visited.contains(k)) { queue.add(k); if (!bfsTraversalPath.containsKey(k)) { bfsTraversalPath.put(k, curr); } } } } return bfsTraversalPath; } // Driver Code public static void main(String[] args) { // Number of edges int n = 7; // Edge List int[][] edges = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 0 }, { 4, 1 }, { 1, 3 } }; // Run the function System.out.println("Minimum Number of Edges to Remove = " + minEdgesRemoval(edges, n)); }} Minimum Number of Edges to Remove = 2 khushboogoyal499 Picked Technical Scripter 2020 Graph Java Java Programs Technical Scripter Java Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Path in a Directed Acyclic Graph Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Graph Coloring | Set 1 (Introduction and Applications) 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": 26311, "s": 26283, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26436, "s": 26311, "text": "Given a connected graph, the task is to find the minimum number of edges to cut/remove to make the given graph disconnected." }, { "code": null, "e": 26546, "s": 26436, "text": "A graph is disconnected if there exists at least two vertices of the graph that are not connected by a path. " }, { "code": null, "e": 26556, "s": 26546, "text": "Examples:" }, { "code": null, "e": 26563, "s": 26556, "text": "Input:" }, { "code": null, "e": 26609, "s": 26563, "text": "Output: Minimum Number of Edges to Remove = 2" }, { "code": null, "e": 26619, "s": 26609, "text": "Approach:" }, { "code": null, "e": 26854, "s": 26619, "text": "The approach to this problem is to find the number of paths in the edge disjoint set of paths from a start vertex to an end vertex in the graph. Edge-disjoint set of paths is a set of paths having no common edge between any two paths." }, { "code": null, "e": 27186, "s": 26854, "text": "Pick one node as start node and another node as end node.Start BFS from the start node and check if a path exists from start node to end node.If yes, then remove all the edges from that path and run BFS again.Repeat step 2 and 3 until there’s no path exists from start node to end node.Return the number of times a path is deleted." }, { "code": null, "e": 27244, "s": 27186, "text": "Pick one node as start node and another node as end node." }, { "code": null, "e": 27330, "s": 27244, "text": "Start BFS from the start node and check if a path exists from start node to end node." }, { "code": null, "e": 27398, "s": 27330, "text": "If yes, then remove all the edges from that path and run BFS again." }, { "code": null, "e": 27476, "s": 27398, "text": "Repeat step 2 and 3 until there’s no path exists from start node to end node." }, { "code": null, "e": 27522, "s": 27476, "text": "Return the number of times a path is deleted." }, { "code": null, "e": 27548, "s": 27522, "text": "Explanation with example:" }, { "code": null, "e": 27554, "s": 27548, "text": "Code:" }, { "code": null, "e": 27559, "s": 27554, "text": "Java" }, { "code": "// Java Program to Find// Minimum Number of Edges// to Cut to make the// Graph Disconnected import java.util.*; public class GFG { // Function to find the min number of edges public static int minEdgesRemoval(int[][] edges, int n) { // Initialize adjacency list for Graph Map<Integer, List<Integer> > graph = new HashMap<Integer, List<Integer> >(); // Initializing starting and ending vertex int start = edges[0][0]; int end = edges[0][1]; // Create adjacency list of the graph for (int i = 0; i < n; i++) { int n1 = edges[i][0]; int n2 = edges[i][1]; List<Integer> li; // Add edges node 1 if (graph.containsKey(n1)) { li = graph.get(n1); } else { li = new ArrayList<Integer>(); } li.add(n2); graph.put(n1, li); // Add edges node 2 if (graph.containsKey(n2)) { li = graph.get(n2); } else { li = new ArrayList<Integer>(); } li.add(n1); graph.put(n2, li); } // Variable to count the number of paths getting // deleted int deleteEdgeCount = 0; while (true) { // bfsTraversalPath is the BFS path from start // to end node It is a map of parent vertex and // child vertex Map<Integer, Integer> bfsTraversalPath = bfs(graph, start); // If end is present on the path from start node // then delete that path and increment // deleteEdgeCount if (bfsTraversalPath.containsKey(end)) { deleteEdgeCount++; int parent = bfsTraversalPath.get(end); int currEnd = end; // Delete all the edges in the current path while (parent != -1) { deleteEdge(graph, parent, currEnd); deleteEdge(graph, currEnd, parent); currEnd = parent; parent = bfsTraversalPath.get(currEnd); } } // If end is not present in the path // then we have a disconnected graph. else { break; } } return deleteEdgeCount; } // Function to delete/remove an edge private static void deleteEdge(Map<Integer, List<Integer> > graph, Integer start, Integer end) { List<Integer> list = graph.get(start); list.remove(end); } // Function for BFS Path private static Map<Integer, Integer> bfs(Map<Integer, List<Integer> > graph, int start) { // Map for BFS Path Map<Integer, Integer> bfsTraversalPath = new HashMap<Integer, Integer>(); // Array for marking visited vertex List<Integer> visited = new ArrayList<Integer>(); // Array for BFS List<Integer> queue = new ArrayList<Integer>(); int qStartIndex = 0; bfsTraversalPath.put(start, -1); queue.add(start); while (qStartIndex < queue.size()) { int curr = queue.get(qStartIndex++); visited.add(curr); for (int k : graph.get(curr)) { if (!visited.contains(k)) { queue.add(k); if (!bfsTraversalPath.containsKey(k)) { bfsTraversalPath.put(k, curr); } } } } return bfsTraversalPath; } // Driver Code public static void main(String[] args) { // Number of edges int n = 7; // Edge List int[][] edges = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 0 }, { 4, 1 }, { 1, 3 } }; // Run the function System.out.println(\"Minimum Number of Edges to Remove = \" + minEdgesRemoval(edges, n)); }}", "e": 31702, "s": 27559, "text": null }, { "code": null, "e": 31743, "s": 31705, "text": "Minimum Number of Edges to Remove = 2" }, { "code": null, "e": 31762, "s": 31745, "text": "khushboogoyal499" }, { "code": null, "e": 31769, "s": 31762, "text": "Picked" }, { "code": null, "e": 31793, "s": 31769, "text": "Technical Scripter 2020" }, { "code": null, "e": 31799, "s": 31793, "text": "Graph" }, { "code": null, "e": 31804, "s": 31799, "text": "Java" }, { "code": null, "e": 31818, "s": 31804, "text": "Java Programs" }, { "code": null, "e": 31837, "s": 31818, "text": "Technical Scripter" }, { "code": null, "e": 31842, "s": 31837, "text": "Java" }, { "code": null, "e": 31848, "s": 31842, "text": "Graph" }, { "code": null, "e": 31946, "s": 31848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31987, "s": 31946, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 32023, "s": 31987, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 32065, "s": 32023, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 32092, "s": 32065, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 32147, "s": 32092, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 32162, "s": 32147, "text": "Arrays in Java" }, { "code": null, "e": 32206, "s": 32162, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32228, "s": 32206, "text": "For-each loop in Java" }, { "code": null, "e": 32279, "s": 32228, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to Add or subtract time span to a datetime in R ? - GeeksforGeeks
30 May, 2021 The time objects in R can be declared either using POSIXct class, which offers fast manipulation and storage of such objects. External packages in R also help in working with time and dates and allow both comparison and direct arithmetic operations to be performed upon them. In this article, we are going to see how to add and subtract a time span to a DateTime in R Programming. Method 1: Using POSIXct object A date string can be first converted to POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to the standard time zone, UTC. A string type date object can be converted to POSIXct object, using them as.POSIXct(date) method in R. Since, the dates are stored in terms of seconds, the subtraction, as well as addition, can be performed by first converting the hours and minutes to the units of seconds too. Mathematical operators can directly be used to add various time components to the date object, which belongs to the POSIXct class. 1 hour = 1 * 60 * 60 seconds 1 min = 1 * 60 seconds Syntax: as.POSIXct ( date , format) Arguments : date – The string date object format – The format specifier of the date Code: R # declaring a datetime objecttime1 <- as.POSIXct("2021-05-08 08:32:07", format = "%Y-%m-%d %H:%M:%S") print ("Original DateTime")print (time1) # adding 20 mins to datetimemins <- 20 * 60print ("Adding 20 mins to DateTime")print (time1 + mins) # converting 3 hours to secondshrs <- 3 * 60 * 60print ("Subtracting 3 hours from DateTime") # subtracting 3 hours from the # date time objectprint (time1 - hrs) Output: [1] "Original DateTime" [1] "2021-05-08 08:32:07 UTC" [1] "Adding 20 mins to DateTime" [1] "2021-05-08 08:52:07 UTC" [1] "Subtracting 3 hours from DateTime" [1] "2021-05-08 05:32:07 UTC" Method 2: Using lubridate package Lubridate package in R is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space by the following command : install.packages("lubridate") The Sys.time() function in R is used to fetch the current date and time object according to the IST zone. The hours() method in R is used to take an input of an integer denoting the number of hours. The “lubridate” package objects allow direct arithmetic over its various components, therefore the number of hours can be directly subtracted from the lubridate time object. A result is also an object belonging to this class. Code: R # getting required librarieslibrary(lubridate) # getting current timetime <- Sys.time()print("Current time")print (time) # subtracting hourshrs <- hours(5) print ("Subtracting 5 hours")mod_time <- time - hrsprint (mod_time)secs <- seconds(17) print ("Adding 17 seconds")mod_time <- time + secsprint (mod_time) Output [1] "Current time" [1] "2021-05-22 03:27:02 IST" [1] "Subtracting 5 hours" [1] "2021-05-21 22:27:02 IST" [1] "Adding 17 seconds" [1] "2021-05-22 03:27:19 IST" Method 3: Using strptime() method strptime method in R is used to directly convert character vectors (of a variety of formats) to POSIXlt format. strptime is faster than the previous approach, because strptime only handles character input. Syntax: strptime(date, format, tz = “”) Arguments : date – The date in character format format – The format specifier of the input date tz – time zone (optional) strptime() works similar to the POSIXct objects, where all the calculations are done in terms of seconds. Code: R # declaring a time objecttime1 <- strptime("2021-07-07 00:32:07", format = "%Y-%m-%d %H:%M:%S")print ("Time")print (time1) # converting 5 hours to secondshrs <- 5 * 60 * 60print ("Subtracting 5 hours")print (time1 - hrs) # adding 48 seconds and 24 mins mins <- 24 * 60secs <- 48 * 60 * 60print ("Modified Time")print ((time1 + mins) - secs) Output: [1] "Time" [1] "2021-07-07 00:32:07 UTC" [1] "Subtracting 5 hours" [1] "2021-07-06 19:32:07 UTC" [1] "Modified Time" [1] "2021-07-05 00:56:07 UTC" Explanation: The subtraction of 5 hours, leads to the return of the previous date. In the second scenario, the respective number of minutes and seconds are computed. Picked R-DateTime 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R Plot mean and standard deviation using ggplot2 in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 May, 2021" }, { "code": null, "e": 26868, "s": 26487, "text": "The time objects in R can be declared either using POSIXct class, which offers fast manipulation and storage of such objects. External packages in R also help in working with time and dates and allow both comparison and direct arithmetic operations to be performed upon them. In this article, we are going to see how to add and subtract a time span to a DateTime in R Programming." }, { "code": null, "e": 26899, "s": 26868, "text": "Method 1: Using POSIXct object" }, { "code": null, "e": 27603, "s": 26899, "text": "A date string can be first converted to POSIXct objects and then basic arithmetic can be performed on it easily. POSIXct objects ease the process of mathematical operations since they rely on seconds as the major unit of time management. The dates are converted to the standard time zone, UTC. A string type date object can be converted to POSIXct object, using them as.POSIXct(date) method in R. Since, the dates are stored in terms of seconds, the subtraction, as well as addition, can be performed by first converting the hours and minutes to the units of seconds too. Mathematical operators can directly be used to add various time components to the date object, which belongs to the POSIXct class. " }, { "code": null, "e": 27655, "s": 27603, "text": "1 hour = 1 * 60 * 60 seconds\n1 min = 1 * 60 seconds" }, { "code": null, "e": 27691, "s": 27655, "text": "Syntax: as.POSIXct ( date , format)" }, { "code": null, "e": 27704, "s": 27691, "text": "Arguments : " }, { "code": null, "e": 27734, "s": 27704, "text": "date – The string date object" }, { "code": null, "e": 27776, "s": 27734, "text": "format – The format specifier of the date" }, { "code": null, "e": 27782, "s": 27776, "text": "Code:" }, { "code": null, "e": 27784, "s": 27782, "text": "R" }, { "code": "# declaring a datetime objecttime1 <- as.POSIXct(\"2021-05-08 08:32:07\", format = \"%Y-%m-%d %H:%M:%S\") print (\"Original DateTime\")print (time1) # adding 20 mins to datetimemins <- 20 * 60print (\"Adding 20 mins to DateTime\")print (time1 + mins) # converting 3 hours to secondshrs <- 3 * 60 * 60print (\"Subtracting 3 hours from DateTime\") # subtracting 3 hours from the # date time objectprint (time1 - hrs)", "e": 28214, "s": 27784, "text": null }, { "code": null, "e": 28222, "s": 28214, "text": "Output:" }, { "code": null, "e": 28409, "s": 28222, "text": "[1] \"Original DateTime\"\n[1] \"2021-05-08 08:32:07 UTC\"\n[1] \"Adding 20 mins to DateTime\"\n[1] \"2021-05-08 08:52:07 UTC\"\n[1] \"Subtracting 3 hours from DateTime\"\n[1] \"2021-05-08 05:32:07 UTC\"" }, { "code": null, "e": 28443, "s": 28409, "text": "Method 2: Using lubridate package" }, { "code": null, "e": 28652, "s": 28443, "text": "Lubridate package in R is used to work with date and time objects. It makes it easier to parse and manipulate the objects and needs to be installed and loaded into the working space by the following command :" }, { "code": null, "e": 28682, "s": 28652, "text": "install.packages(\"lubridate\")" }, { "code": null, "e": 29108, "s": 28682, "text": "The Sys.time() function in R is used to fetch the current date and time object according to the IST zone. The hours() method in R is used to take an input of an integer denoting the number of hours. The “lubridate” package objects allow direct arithmetic over its various components, therefore the number of hours can be directly subtracted from the lubridate time object. A result is also an object belonging to this class." }, { "code": null, "e": 29114, "s": 29108, "text": "Code:" }, { "code": null, "e": 29116, "s": 29114, "text": "R" }, { "code": "# getting required librarieslibrary(lubridate) # getting current timetime <- Sys.time()print(\"Current time\")print (time) # subtracting hourshrs <- hours(5) print (\"Subtracting 5 hours\")mod_time <- time - hrsprint (mod_time)secs <- seconds(17) print (\"Adding 17 seconds\")mod_time <- time + secsprint (mod_time)", "e": 29430, "s": 29116, "text": null }, { "code": null, "e": 29437, "s": 29430, "text": "Output" }, { "code": null, "e": 29601, "s": 29437, "text": "[1] \"Current time\" \n[1] \"2021-05-22 03:27:02 IST\" \n[1] \"Subtracting 5 hours\" \n[1] \"2021-05-21 22:27:02 IST\" \n[1] \"Adding 17 seconds\" \n[1] \"2021-05-22 03:27:19 IST\"" }, { "code": null, "e": 29635, "s": 29601, "text": "Method 3: Using strptime() method" }, { "code": null, "e": 29841, "s": 29635, "text": "strptime method in R is used to directly convert character vectors (of a variety of formats) to POSIXlt format. strptime is faster than the previous approach, because strptime only handles character input." }, { "code": null, "e": 29881, "s": 29841, "text": "Syntax: strptime(date, format, tz = “”)" }, { "code": null, "e": 29893, "s": 29881, "text": "Arguments :" }, { "code": null, "e": 29929, "s": 29893, "text": "date – The date in character format" }, { "code": null, "e": 29977, "s": 29929, "text": "format – The format specifier of the input date" }, { "code": null, "e": 30003, "s": 29977, "text": "tz – time zone (optional)" }, { "code": null, "e": 30110, "s": 30003, "text": "strptime() works similar to the POSIXct objects, where all the calculations are done in terms of seconds. " }, { "code": null, "e": 30116, "s": 30110, "text": "Code:" }, { "code": null, "e": 30118, "s": 30116, "text": "R" }, { "code": "# declaring a time objecttime1 <- strptime(\"2021-07-07 00:32:07\", format = \"%Y-%m-%d %H:%M:%S\")print (\"Time\")print (time1) # converting 5 hours to secondshrs <- 5 * 60 * 60print (\"Subtracting 5 hours\")print (time1 - hrs) # adding 48 seconds and 24 mins mins <- 24 * 60secs <- 48 * 60 * 60print (\"Modified Time\")print ((time1 + mins) - secs)", "e": 30480, "s": 30118, "text": null }, { "code": null, "e": 30488, "s": 30480, "text": "Output:" }, { "code": null, "e": 30635, "s": 30488, "text": "[1] \"Time\"\n[1] \"2021-07-07 00:32:07 UTC\"\n[1] \"Subtracting 5 hours\"\n[1] \"2021-07-06 19:32:07 UTC\"\n[1] \"Modified Time\"\n[1] \"2021-07-05 00:56:07 UTC\"" }, { "code": null, "e": 30801, "s": 30635, "text": "Explanation: The subtraction of 5 hours, leads to the return of the previous date. In the second scenario, the respective number of minutes and seconds are computed." }, { "code": null, "e": 30808, "s": 30801, "text": "Picked" }, { "code": null, "e": 30819, "s": 30808, "text": "R-DateTime" }, { "code": null, "e": 30830, "s": 30819, "text": "R Language" }, { "code": null, "e": 30928, "s": 30830, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30980, "s": 30928, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31015, "s": 30980, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 31053, "s": 31015, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 31111, "s": 31053, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31154, "s": 31111, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31203, "s": 31154, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31240, "s": 31203, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 31257, "s": 31240, "text": "R - if statement" }, { "code": null, "e": 31283, "s": 31257, "text": "Time Series Analysis in R" } ]
How to create and read value from cookie ? - GeeksforGeeks
31 Mar, 2020 The web servers host the website. The client-server makes a request for data from the webserver and the webserver fetches the required pages and responds to the client by sending the requested pages. The web server communicates with the client-server using HTTP (HyperText Transfer Protocol). HTTP is a stateless protocol which means the server needs not to retain the user information once the transaction ends and the connection is closed. The web browser is an example of a client-server which communicates with the web server using HTTP. HTTP prevents long engagement of the client with the webserver and the connection is closed automatically once the request is serviced. But often it is required to store the user information for future references. One of the most common uses of cookies is for authentication. Cookies serve the purpose of retaining user information even when the connection is lost. Cookies are data, stored in text files, on the computer. Cookies comprise of five variable fields: Expires:Specifies when the cookie will expire. If left empty the cookie expires immediately when the connection is lost. Domain: Specifies the domain name of the website. Name=Value: Cookies are stored in the form of name-value pairs. Path: Specifies the webpage or directory that sets the cookie. Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure). However, cookies can store only a small amount of data like userID or sessionID. Clearing the cookies will logout the user of every site that it had logged in. HTTP can be made stateful by using cookies. Stateful web applications store the information from the previous requests and can use it for serving future requests. Working Principle: When the client or web browser establishes a connection with the webserver, the webserver sends some data to the browser in the form of a cookie. The browser may accept or reject the cookie. If the browser accepts it, the cookie gets stored in the hard disk of the client device. The CGI scripts on the server can read and write cookie values that are stored on the client, so when the client visits the same website again it retrieves the cookie data from the browser. JavaScript can be used to manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies for the current web page. The code below demonstrates how JavaScript can be used to create and read a value from the cookie. Create cookie using JavaScript: This function creates a cookie using the field-name, field-value, and expiry date. The path is left blank such that it applies to the current webpage. However, we can specify any other webpage or directory name. Program: function createCookie(fieldname, fieldvalue, expiry) { var date = new Date(); date.setTime(date.getTime()+ (expiry*24*60*60*1000)); var expires = "expires=" + date.toGMTString(); document.cookie = fieldname + "=" + fieldvalue + ";" + expires + ";path=/";} Read cookie using JavaScript: This function retrieves the cookie data stored in the browser. The cookie string is automatically encoded while sending it from the server to the browser. Hence it needs to be decoded before the actual data can be retrieved. Next, the decoded string is split into an array to get all the cookie name-value pairs. Loop through the array to find the field-name and respective field-values. If the cookie is found, the value is returned else the function returns the empty string. Program: function readCookie(cname) { var name = cname + "="; var decoded_cookie = decodeURIComponent(document.cookie); var carr = decoded_cookie.split(';'); for(var i=0; i<carr.length;i++){ var c = carr[i]; while(c.charAt(0)==' '){ c=c.substring(1); } if(c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return "";} Create and read cookies using JavaScript: When the webpage is loaded the runApp() function is called and it checks if there exists a cookie in the browser it is retrieved else a new cookie is created for the same. Program: <!DOCTYPE html><html><head> <title> Create and read cookies using JavaScript </title> <script type="text/javascript"> function createCookie(fieldname, fieldvalue, expiry) { var date = new Date(); date.setTime(date.getTime()+ (expiry*24*60*60*1000)); var expires = "expires=" + date.toGMTString(); document.cookie = fieldname + "=" + fieldvalue + ";" + expires + ";path=/"; } function readCookie(cname) { var name = cname + "="; var decoded_cookie = decodeURIComponent(document.cookie); var carr = decoded_cookie.split(';'); for(var i=0; i<carr.length;i++){ var c = carr[i]; while(c.charAt(0)==' '){ c=c.substring(1); } if(c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function runApp() { var user = readCookie("username"); if(user != ""){ alert("Hello "+user); }else{ user=prompt("Enter your name: ", ""); if(user!= "" && user!=null){ createCookie("username", user, 30); } } } </script></head><body onload="runApp()"></body></html> Output: Creating Cookie: Reading Cookie: HTML-Misc JavaScript-Misc Picked HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26139, "s": 26111, "text": "\n31 Mar, 2020" }, { "code": null, "e": 27104, "s": 26139, "text": "The web servers host the website. The client-server makes a request for data from the webserver and the webserver fetches the required pages and responds to the client by sending the requested pages. The web server communicates with the client-server using HTTP (HyperText Transfer Protocol). HTTP is a stateless protocol which means the server needs not to retain the user information once the transaction ends and the connection is closed. The web browser is an example of a client-server which communicates with the web server using HTTP. HTTP prevents long engagement of the client with the webserver and the connection is closed automatically once the request is serviced. But often it is required to store the user information for future references. One of the most common uses of cookies is for authentication. Cookies serve the purpose of retaining user information even when the connection is lost. Cookies are data, stored in text files, on the computer." }, { "code": null, "e": 27146, "s": 27104, "text": "Cookies comprise of five variable fields:" }, { "code": null, "e": 27267, "s": 27146, "text": "Expires:Specifies when the cookie will expire. If left empty the cookie expires immediately when the connection is lost." }, { "code": null, "e": 27317, "s": 27267, "text": "Domain: Specifies the domain name of the website." }, { "code": null, "e": 27381, "s": 27317, "text": "Name=Value: Cookies are stored in the form of name-value pairs." }, { "code": null, "e": 27444, "s": 27381, "text": "Path: Specifies the webpage or directory that sets the cookie." }, { "code": null, "e": 27536, "s": 27444, "text": "Secure: Specifies whether the cookie can be retrieved by any server (secure or non-secure)." }, { "code": null, "e": 27859, "s": 27536, "text": "However, cookies can store only a small amount of data like userID or sessionID. Clearing the cookies will logout the user of every site that it had logged in. HTTP can be made stateful by using cookies. Stateful web applications store the information from the previous requests and can use it for serving future requests." }, { "code": null, "e": 28628, "s": 27859, "text": "Working Principle: When the client or web browser establishes a connection with the webserver, the webserver sends some data to the browser in the form of a cookie. The browser may accept or reject the cookie. If the browser accepts it, the cookie gets stored in the hard disk of the client device. The CGI scripts on the server can read and write cookie values that are stored on the client, so when the client visits the same website again it retrieves the cookie data from the browser. JavaScript can be used to manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies for the current web page. The code below demonstrates how JavaScript can be used to create and read a value from the cookie." }, { "code": null, "e": 28872, "s": 28628, "text": "Create cookie using JavaScript: This function creates a cookie using the field-name, field-value, and expiry date. The path is left blank such that it applies to the current webpage. However, we can specify any other webpage or directory name." }, { "code": null, "e": 28881, "s": 28872, "text": "Program:" }, { "code": "function createCookie(fieldname, fieldvalue, expiry) { var date = new Date(); date.setTime(date.getTime()+ (expiry*24*60*60*1000)); var expires = \"expires=\" + date.toGMTString(); document.cookie = fieldname + \"=\" + fieldvalue + \";\" + expires + \";path=/\";}", "e": 29171, "s": 28881, "text": null }, { "code": null, "e": 29679, "s": 29171, "text": "Read cookie using JavaScript: This function retrieves the cookie data stored in the browser. The cookie string is automatically encoded while sending it from the server to the browser. Hence it needs to be decoded before the actual data can be retrieved. Next, the decoded string is split into an array to get all the cookie name-value pairs. Loop through the array to find the field-name and respective field-values. If the cookie is found, the value is returned else the function returns the empty string." }, { "code": null, "e": 29688, "s": 29679, "text": "Program:" }, { "code": "function readCookie(cname) { var name = cname + \"=\"; var decoded_cookie = decodeURIComponent(document.cookie); var carr = decoded_cookie.split(';'); for(var i=0; i<carr.length;i++){ var c = carr[i]; while(c.charAt(0)==' '){ c=c.substring(1); } if(c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return \"\";}", "e": 30067, "s": 29688, "text": null }, { "code": null, "e": 30281, "s": 30067, "text": "Create and read cookies using JavaScript: When the webpage is loaded the runApp() function is called and it checks if there exists a cookie in the browser it is retrieved else a new cookie is created for the same." }, { "code": null, "e": 30290, "s": 30281, "text": "Program:" }, { "code": "<!DOCTYPE html><html><head> <title> Create and read cookies using JavaScript </title> <script type=\"text/javascript\"> function createCookie(fieldname, fieldvalue, expiry) { var date = new Date(); date.setTime(date.getTime()+ (expiry*24*60*60*1000)); var expires = \"expires=\" + date.toGMTString(); document.cookie = fieldname + \"=\" + fieldvalue + \";\" + expires + \";path=/\"; } function readCookie(cname) { var name = cname + \"=\"; var decoded_cookie = decodeURIComponent(document.cookie); var carr = decoded_cookie.split(';'); for(var i=0; i<carr.length;i++){ var c = carr[i]; while(c.charAt(0)==' '){ c=c.substring(1); } if(c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return \"\"; } function runApp() { var user = readCookie(\"username\"); if(user != \"\"){ alert(\"Hello \"+user); }else{ user=prompt(\"Enter your name: \", \"\"); if(user!= \"\" && user!=null){ createCookie(\"username\", user, 30); } } } </script></head><body onload=\"runApp()\"></body></html>", "e": 31733, "s": 30290, "text": null }, { "code": null, "e": 31741, "s": 31733, "text": "Output:" }, { "code": null, "e": 31758, "s": 31741, "text": "Creating Cookie:" }, { "code": null, "e": 31774, "s": 31758, "text": "Reading Cookie:" }, { "code": null, "e": 31784, "s": 31774, "text": "HTML-Misc" }, { "code": null, "e": 31800, "s": 31784, "text": "JavaScript-Misc" }, { "code": null, "e": 31807, "s": 31800, "text": "Picked" }, { "code": null, "e": 31812, "s": 31807, "text": "HTML" }, { "code": null, "e": 31823, "s": 31812, "text": "JavaScript" }, { "code": null, "e": 31840, "s": 31823, "text": "Web Technologies" }, { "code": null, "e": 31867, "s": 31840, "text": "Web technologies Questions" }, { "code": null, "e": 31872, "s": 31867, "text": "HTML" }, { "code": null, "e": 31970, "s": 31872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31994, "s": 31970, "text": "REST API (Introduction)" }, { "code": null, "e": 32035, "s": 31994, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 32072, "s": 32035, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32101, "s": 32072, "text": "Form validation using jQuery" }, { "code": null, "e": 32121, "s": 32101, "text": "Angular File Upload" }, { "code": null, "e": 32161, "s": 32121, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32206, "s": 32161, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32267, "s": 32206, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32339, "s": 32267, "text": "Differences between Functional Components and Class Components in React" } ]
House of Quality Example in Software Quality - GeeksforGeeks
31 Aug, 2020 Prerequisite – Quality Function Deployment (QFD) House of Quality and its parts have been discussed in prerequisite article. Here, we will understand how to construct a house of quality from scratch. Question :Construct House of Quality diagram for product – CHOCOLATE. Let’s first identify Customer requirements (WHATs) and design or technical specifications (HOWs) : WHATs for product – chocolate could be :Appetizing appearanceGood textureFlavorsLow priceHealthy and Low fatsGood taste Appetizing appearanceGood textureFlavorsLow priceHealthy and Low fatsGood taste Appetizing appearance Good texture Flavors Low price Healthy and Low fats Good taste HOWs for the product – chocolate are :ColorWeightSize/DimensionPackagingChoice of flavorsQuantity of milkSugar content ColorWeightSize/DimensionPackagingChoice of flavorsQuantity of milkSugar content Color Weight Size/Dimension Packaging Choice of flavors Quantity of milk Sugar content Now, let’s fill all of them in House of Quality diagram : Now, let’s make use of body ranking system shown below and assign rank symbols in body of house of quality by identifying correlation between WHATs and HOWs. Strong correlation exists between :Appetizing appearance – ColorGood texture – ColorGood texture – PackagingFlavors – Choice of flavorsFlavors – Sugar contentHealthy and Low fats – Quantity of MilkGood taste – Sugar content Appetizing appearance – ColorGood texture – ColorGood texture – PackagingFlavors – Choice of flavorsFlavors – Sugar contentHealthy and Low fats – Quantity of MilkGood taste – Sugar content Appetizing appearance – Color Good texture – Color Good texture – Packaging Flavors – Choice of flavors Flavors – Sugar content Healthy and Low fats – Quantity of Milk Good taste – Sugar content Moderate correlation exists between :Appetizing appearance – WeightAppetizing appearance – PackagingAppetizing appearance – Choice of flavorsLow price – Size/DimensionLow price – Quantity of MilkGood taste – Choice of flavorsGood taste – Quantity of Milk Appetizing appearance – WeightAppetizing appearance – PackagingAppetizing appearance – Choice of flavorsLow price – Size/DimensionLow price – Quantity of MilkGood taste – Choice of flavorsGood taste – Quantity of Milk Appetizing appearance – Weight Appetizing appearance – Packaging Appetizing appearance – Choice of flavors Low price – Size/Dimension Low price – Quantity of Milk Good taste – Choice of flavors Good taste – Quantity of Milk Weak correlation exists between :Appetizing appearance – Size/DimensionAppetizing appearance – Quantity of MilkFlavors – Quantity of MilkLow price – Choice of flavorsHealthy and Low fats – Choice of flavorsGood taste – Packaging Appetizing appearance – Size/DimensionAppetizing appearance – Quantity of MilkFlavors – Quantity of MilkLow price – Choice of flavorsHealthy and Low fats – Choice of flavorsGood taste – Packaging Appetizing appearance – Size/Dimension Appetizing appearance – Quantity of Milk Flavors – Quantity of Milk Low price – Choice of flavors Healthy and Low fats – Choice of flavors Good taste – Packaging The rest of cells in body of matrix have no correlation, so they are left empty. Importance factor is assigned by team on basis of prioritized customer requirements. In our example, let’s assign importance factor as follows :Appetizing appearance – 2Good texture – 3Flavors – 3Low price – 1Healthy and Low fats – 4Good taste – 5After filling body, house of quality diagram will be as follows :Now, let’s fill roof of house of quality in a similar manner by following roof ranking system given below.Strong positive Interaction :Weight – SizePositive Interaction :Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milkNegative Interaction :Weight – Choice of flavorStrong negative Interaction :Color – WeightColor – SizeSize – Quantity of milkSize – Sugar contentThe rest of interactions are None Updated house of quality diagram is shown below :The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers.Now, let’s calculate Importance Weight and Relative Importance Weight.Importance Weight (Color) = 9 * 2 + 3 * 9 + 3 * 1 = 48 Importance Weight (Weight) = 3 * 2 = 6 Importance Weight (Size) = 2 * 1 + 1 * 3 = 5 Importance Weight (Packaging) = 2 * 3 + 3 * 9 + 5 * 1 = 38 Importance Weight (Choice of flavor) = 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53 Importance Weight (Quantity of milk) = 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59 Importance Weight (Sugar content) = 3 * 9 + 5 * 9 = 72 Total Importance Weight = 48 + 6 + 5 + 38 + 53 + 59 + 72 = 281Now, Relative Importance Weight :Relative Importance Weight (Color) = ( 48 / 281 ) * 100 = 17.1 Relative Importance Weight (Weight) = ( 6 / 281 ) * 100 = 2.14 Relative Importance Weight (Size) = ( 5 / 281 ) * 100 = 1.78 Relative Importance Weight (Packaging) = ( 38 / 281 ) * 100 = 13.5 Relative Importance Weight (Choice of flavor) = ( 53 / 281 ) * 100 = 18.86 Relative Importance Weight (Quantity of milk) = ( 59 / 281 ) * 100 = 21.0 Relative Importance Weight (Sugar content) = ( 72 / 281 ) * 100 = 25.6 Now, we need to fill these values in house of quality. The final house of quality diagram is shown below :Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products.My Personal Notes arrow_drop_upSave Appetizing appearance – 2Good texture – 3Flavors – 3Low price – 1Healthy and Low fats – 4Good taste – 5 Appetizing appearance – 2 Good texture – 3 Flavors – 3 Low price – 1 Healthy and Low fats – 4 Good taste – 5 After filling body, house of quality diagram will be as follows : Now, let’s fill roof of house of quality in a similar manner by following roof ranking system given below. Strong positive Interaction :Weight – Size Weight – Size Weight – Size Positive Interaction :Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milk Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milk Color – Choice of flavor Color – Quantity of milk Weight – Packaging Size – Packaging Choice of flavor – Sugar content Choice of flavor – Quantity of milk Negative Interaction :Weight – Choice of flavor Weight – Choice of flavor Weight – Choice of flavor Strong negative Interaction :Color – WeightColor – SizeSize – Quantity of milkSize – Sugar content Color – WeightColor – SizeSize – Quantity of milkSize – Sugar content Color – Weight Color – Size Size – Quantity of milk Size – Sugar content The rest of interactions are None Updated house of quality diagram is shown below :The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers.Now, let’s calculate Importance Weight and Relative Importance Weight.Importance Weight (Color) = 9 * 2 + 3 * 9 + 3 * 1 = 48 Importance Weight (Weight) = 3 * 2 = 6 Importance Weight (Size) = 2 * 1 + 1 * 3 = 5 Importance Weight (Packaging) = 2 * 3 + 3 * 9 + 5 * 1 = 38 Importance Weight (Choice of flavor) = 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53 Importance Weight (Quantity of milk) = 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59 Importance Weight (Sugar content) = 3 * 9 + 5 * 9 = 72 Total Importance Weight = 48 + 6 + 5 + 38 + 53 + 59 + 72 = 281Now, Relative Importance Weight :Relative Importance Weight (Color) = ( 48 / 281 ) * 100 = 17.1 Relative Importance Weight (Weight) = ( 6 / 281 ) * 100 = 2.14 Relative Importance Weight (Size) = ( 5 / 281 ) * 100 = 1.78 Relative Importance Weight (Packaging) = ( 38 / 281 ) * 100 = 13.5 Relative Importance Weight (Choice of flavor) = ( 53 / 281 ) * 100 = 18.86 Relative Importance Weight (Quantity of milk) = ( 59 / 281 ) * 100 = 21.0 Relative Importance Weight (Sugar content) = ( 72 / 281 ) * 100 = 25.6 Now, we need to fill these values in house of quality. The final house of quality diagram is shown below :Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products.My Personal Notes arrow_drop_upSave The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers. Now, let’s calculate Importance Weight and Relative Importance Weight. Importance Weight (Color) = 9 * 2 + 3 * 9 + 3 * 1 = 48 Importance Weight (Weight) = 3 * 2 = 6 Importance Weight (Size) = 2 * 1 + 1 * 3 = 5 Importance Weight (Packaging) = 2 * 3 + 3 * 9 + 5 * 1 = 38 Importance Weight (Choice of flavor) = 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53 Importance Weight (Quantity of milk) = 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59 Importance Weight (Sugar content) = 3 * 9 + 5 * 9 = 72 Total Importance Weight = 48 + 6 + 5 + 38 + 53 + 59 + 72 = 281 Now, Relative Importance Weight : Relative Importance Weight (Color) = ( 48 / 281 ) * 100 = 17.1 Relative Importance Weight (Weight) = ( 6 / 281 ) * 100 = 2.14 Relative Importance Weight (Size) = ( 5 / 281 ) * 100 = 1.78 Relative Importance Weight (Packaging) = ( 38 / 281 ) * 100 = 13.5 Relative Importance Weight (Choice of flavor) = ( 53 / 281 ) * 100 = 18.86 Relative Importance Weight (Quantity of milk) = ( 59 / 281 ) * 100 = 21.0 Relative Importance Weight (Sugar content) = ( 72 / 281 ) * 100 = 25.6 Now, we need to fill these values in house of quality. The final house of quality diagram is shown below : Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products. Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Software Engineering | Integration Testing System Testing Software Engineering | Black box testing Software Engineering | Software Quality Assurance What is DFD(Data Flow Diagram)? Difference between IAAS, PAAS and SAAS Difference between Unit Testing and Integration Testing Use Case Diagram for Library Management System Object Oriented Analysis and Design Software Development Life Cycle (SDLC)
[ { "code": null, "e": 26235, "s": 26207, "text": "\n31 Aug, 2020" }, { "code": null, "e": 26284, "s": 26235, "text": "Prerequisite – Quality Function Deployment (QFD)" }, { "code": null, "e": 26435, "s": 26284, "text": "House of Quality and its parts have been discussed in prerequisite article. Here, we will understand how to construct a house of quality from scratch." }, { "code": null, "e": 26505, "s": 26435, "text": "Question :Construct House of Quality diagram for product – CHOCOLATE." }, { "code": null, "e": 26604, "s": 26505, "text": "Let’s first identify Customer requirements (WHATs) and design or technical specifications (HOWs) :" }, { "code": null, "e": 26724, "s": 26604, "text": "WHATs for product – chocolate could be :Appetizing appearanceGood textureFlavorsLow priceHealthy and Low fatsGood taste" }, { "code": null, "e": 26804, "s": 26724, "text": "Appetizing appearanceGood textureFlavorsLow priceHealthy and Low fatsGood taste" }, { "code": null, "e": 26826, "s": 26804, "text": "Appetizing appearance" }, { "code": null, "e": 26839, "s": 26826, "text": "Good texture" }, { "code": null, "e": 26847, "s": 26839, "text": "Flavors" }, { "code": null, "e": 26857, "s": 26847, "text": "Low price" }, { "code": null, "e": 26878, "s": 26857, "text": "Healthy and Low fats" }, { "code": null, "e": 26889, "s": 26878, "text": "Good taste" }, { "code": null, "e": 27008, "s": 26889, "text": "HOWs for the product – chocolate are :ColorWeightSize/DimensionPackagingChoice of flavorsQuantity of milkSugar content" }, { "code": null, "e": 27089, "s": 27008, "text": "ColorWeightSize/DimensionPackagingChoice of flavorsQuantity of milkSugar content" }, { "code": null, "e": 27095, "s": 27089, "text": "Color" }, { "code": null, "e": 27102, "s": 27095, "text": "Weight" }, { "code": null, "e": 27117, "s": 27102, "text": "Size/Dimension" }, { "code": null, "e": 27127, "s": 27117, "text": "Packaging" }, { "code": null, "e": 27145, "s": 27127, "text": "Choice of flavors" }, { "code": null, "e": 27162, "s": 27145, "text": "Quantity of milk" }, { "code": null, "e": 27176, "s": 27162, "text": "Sugar content" }, { "code": null, "e": 27234, "s": 27176, "text": "Now, let’s fill all of them in House of Quality diagram :" }, { "code": null, "e": 27392, "s": 27234, "text": "Now, let’s make use of body ranking system shown below and assign rank symbols in body of house of quality by identifying correlation between WHATs and HOWs." }, { "code": null, "e": 27616, "s": 27392, "text": "Strong correlation exists between :Appetizing appearance – ColorGood texture – ColorGood texture – PackagingFlavors – Choice of flavorsFlavors – Sugar contentHealthy and Low fats – Quantity of MilkGood taste – Sugar content" }, { "code": null, "e": 27805, "s": 27616, "text": "Appetizing appearance – ColorGood texture – ColorGood texture – PackagingFlavors – Choice of flavorsFlavors – Sugar contentHealthy and Low fats – Quantity of MilkGood taste – Sugar content" }, { "code": null, "e": 27835, "s": 27805, "text": "Appetizing appearance – Color" }, { "code": null, "e": 27856, "s": 27835, "text": "Good texture – Color" }, { "code": null, "e": 27881, "s": 27856, "text": "Good texture – Packaging" }, { "code": null, "e": 27909, "s": 27881, "text": "Flavors – Choice of flavors" }, { "code": null, "e": 27933, "s": 27909, "text": "Flavors – Sugar content" }, { "code": null, "e": 27973, "s": 27933, "text": "Healthy and Low fats – Quantity of Milk" }, { "code": null, "e": 28000, "s": 27973, "text": "Good taste – Sugar content" }, { "code": null, "e": 28255, "s": 28000, "text": "Moderate correlation exists between :Appetizing appearance – WeightAppetizing appearance – PackagingAppetizing appearance – Choice of flavorsLow price – Size/DimensionLow price – Quantity of MilkGood taste – Choice of flavorsGood taste – Quantity of Milk" }, { "code": null, "e": 28473, "s": 28255, "text": "Appetizing appearance – WeightAppetizing appearance – PackagingAppetizing appearance – Choice of flavorsLow price – Size/DimensionLow price – Quantity of MilkGood taste – Choice of flavorsGood taste – Quantity of Milk" }, { "code": null, "e": 28504, "s": 28473, "text": "Appetizing appearance – Weight" }, { "code": null, "e": 28538, "s": 28504, "text": "Appetizing appearance – Packaging" }, { "code": null, "e": 28580, "s": 28538, "text": "Appetizing appearance – Choice of flavors" }, { "code": null, "e": 28607, "s": 28580, "text": "Low price – Size/Dimension" }, { "code": null, "e": 28636, "s": 28607, "text": "Low price – Quantity of Milk" }, { "code": null, "e": 28667, "s": 28636, "text": "Good taste – Choice of flavors" }, { "code": null, "e": 28697, "s": 28667, "text": "Good taste – Quantity of Milk" }, { "code": null, "e": 28926, "s": 28697, "text": "Weak correlation exists between :Appetizing appearance – Size/DimensionAppetizing appearance – Quantity of MilkFlavors – Quantity of MilkLow price – Choice of flavorsHealthy and Low fats – Choice of flavorsGood taste – Packaging" }, { "code": null, "e": 29122, "s": 28926, "text": "Appetizing appearance – Size/DimensionAppetizing appearance – Quantity of MilkFlavors – Quantity of MilkLow price – Choice of flavorsHealthy and Low fats – Choice of flavorsGood taste – Packaging" }, { "code": null, "e": 29161, "s": 29122, "text": "Appetizing appearance – Size/Dimension" }, { "code": null, "e": 29202, "s": 29161, "text": "Appetizing appearance – Quantity of Milk" }, { "code": null, "e": 29229, "s": 29202, "text": "Flavors – Quantity of Milk" }, { "code": null, "e": 29259, "s": 29229, "text": "Low price – Choice of flavors" }, { "code": null, "e": 29300, "s": 29259, "text": "Healthy and Low fats – Choice of flavors" }, { "code": null, "e": 29323, "s": 29300, "text": "Good taste – Packaging" }, { "code": null, "e": 31794, "s": 29323, "text": "The rest of cells in body of matrix have no correlation, so they are left empty. Importance factor is assigned by team on basis of prioritized customer requirements. In our example, let’s assign importance factor as follows :Appetizing appearance – 2Good texture – 3Flavors – 3Low price – 1Healthy and Low fats – 4Good taste – 5After filling body, house of quality diagram will be as follows :Now, let’s fill roof of house of quality in a similar manner by following roof ranking system given below.Strong positive Interaction :Weight – SizePositive Interaction :Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milkNegative Interaction :Weight – Choice of flavorStrong negative Interaction :Color – WeightColor – SizeSize – Quantity of milkSize – Sugar contentThe rest of interactions are None Updated house of quality diagram is shown below :The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers.Now, let’s calculate Importance Weight and Relative Importance Weight.Importance Weight (Color) \n= 9 * 2 + 3 * 9 + 3 * 1 = 48\n\nImportance Weight (Weight) \n= 3 * 2 = 6\n\nImportance Weight (Size) \n= 2 * 1 + 1 * 3 = 5\n\nImportance Weight (Packaging) \n= 2 * 3 + 3 * 9 + 5 * 1 = 38\n\nImportance Weight (Choice of flavor) \n= 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53\n\nImportance Weight (Quantity of milk) \n= 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59\n\nImportance Weight (Sugar content) \n= 3 * 9 + 5 * 9 = 72\n\nTotal Importance Weight \n= 48 + 6 + 5 + 38 + 53 + 59 + 72 \n= 281Now, Relative Importance Weight :Relative Importance Weight (Color) \n= ( 48 / 281 ) * 100 = 17.1\n\nRelative Importance Weight (Weight) \n= ( 6 / 281 ) * 100 = 2.14\n\nRelative Importance Weight (Size) \n= ( 5 / 281 ) * 100 = 1.78\n\nRelative Importance Weight (Packaging) \n= ( 38 / 281 ) * 100 = 13.5 \n\nRelative Importance Weight (Choice of flavor) \n= ( 53 / 281 ) * 100 = 18.86\n\nRelative Importance Weight (Quantity of milk) \n= ( 59 / 281 ) * 100 = 21.0\n\nRelative Importance Weight (Sugar content) \n= ( 72 / 281 ) * 100 = 25.6\nNow, we need to fill these values in house of quality. The final house of quality diagram is shown below :Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31898, "s": 31794, "text": "Appetizing appearance – 2Good texture – 3Flavors – 3Low price – 1Healthy and Low fats – 4Good taste – 5" }, { "code": null, "e": 31924, "s": 31898, "text": "Appetizing appearance – 2" }, { "code": null, "e": 31941, "s": 31924, "text": "Good texture – 3" }, { "code": null, "e": 31953, "s": 31941, "text": "Flavors – 3" }, { "code": null, "e": 31967, "s": 31953, "text": "Low price – 1" }, { "code": null, "e": 31992, "s": 31967, "text": "Healthy and Low fats – 4" }, { "code": null, "e": 32007, "s": 31992, "text": "Good taste – 5" }, { "code": null, "e": 32073, "s": 32007, "text": "After filling body, house of quality diagram will be as follows :" }, { "code": null, "e": 32180, "s": 32073, "text": "Now, let’s fill roof of house of quality in a similar manner by following roof ranking system given below." }, { "code": null, "e": 32223, "s": 32180, "text": "Strong positive Interaction :Weight – Size" }, { "code": null, "e": 32237, "s": 32223, "text": "Weight – Size" }, { "code": null, "e": 32251, "s": 32237, "text": "Weight – Size" }, { "code": null, "e": 32423, "s": 32251, "text": "Positive Interaction :Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milk" }, { "code": null, "e": 32573, "s": 32423, "text": "Color – Choice of flavorColor – Quantity of milkWeight – PackagingSize – PackagingChoice of flavor – Sugar contentChoice of flavor – Quantity of milk" }, { "code": null, "e": 32598, "s": 32573, "text": "Color – Choice of flavor" }, { "code": null, "e": 32623, "s": 32598, "text": "Color – Quantity of milk" }, { "code": null, "e": 32642, "s": 32623, "text": "Weight – Packaging" }, { "code": null, "e": 32659, "s": 32642, "text": "Size – Packaging" }, { "code": null, "e": 32692, "s": 32659, "text": "Choice of flavor – Sugar content" }, { "code": null, "e": 32728, "s": 32692, "text": "Choice of flavor – Quantity of milk" }, { "code": null, "e": 32776, "s": 32728, "text": "Negative Interaction :Weight – Choice of flavor" }, { "code": null, "e": 32802, "s": 32776, "text": "Weight – Choice of flavor" }, { "code": null, "e": 32828, "s": 32802, "text": "Weight – Choice of flavor" }, { "code": null, "e": 32927, "s": 32828, "text": "Strong negative Interaction :Color – WeightColor – SizeSize – Quantity of milkSize – Sugar content" }, { "code": null, "e": 32997, "s": 32927, "text": "Color – WeightColor – SizeSize – Quantity of milkSize – Sugar content" }, { "code": null, "e": 33012, "s": 32997, "text": "Color – Weight" }, { "code": null, "e": 33025, "s": 33012, "text": "Color – Size" }, { "code": null, "e": 33049, "s": 33025, "text": "Size – Quantity of milk" }, { "code": null, "e": 33070, "s": 33049, "text": "Size – Sugar content" }, { "code": null, "e": 34684, "s": 33070, "text": "The rest of interactions are None Updated house of quality diagram is shown below :The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers.Now, let’s calculate Importance Weight and Relative Importance Weight.Importance Weight (Color) \n= 9 * 2 + 3 * 9 + 3 * 1 = 48\n\nImportance Weight (Weight) \n= 3 * 2 = 6\n\nImportance Weight (Size) \n= 2 * 1 + 1 * 3 = 5\n\nImportance Weight (Packaging) \n= 2 * 3 + 3 * 9 + 5 * 1 = 38\n\nImportance Weight (Choice of flavor) \n= 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53\n\nImportance Weight (Quantity of milk) \n= 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59\n\nImportance Weight (Sugar content) \n= 3 * 9 + 5 * 9 = 72\n\nTotal Importance Weight \n= 48 + 6 + 5 + 38 + 53 + 59 + 72 \n= 281Now, Relative Importance Weight :Relative Importance Weight (Color) \n= ( 48 / 281 ) * 100 = 17.1\n\nRelative Importance Weight (Weight) \n= ( 6 / 281 ) * 100 = 2.14\n\nRelative Importance Weight (Size) \n= ( 5 / 281 ) * 100 = 1.78\n\nRelative Importance Weight (Packaging) \n= ( 38 / 281 ) * 100 = 13.5 \n\nRelative Importance Weight (Choice of flavor) \n= ( 53 / 281 ) * 100 = 18.86\n\nRelative Importance Weight (Quantity of milk) \n= ( 59 / 281 ) * 100 = 21.0\n\nRelative Importance Weight (Sugar content) \n= ( 72 / 281 ) * 100 = 25.6\nNow, we need to fill these values in house of quality. The final house of quality diagram is shown below :Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34860, "s": 34684, "text": "The next step is to fill competitor comparison part. So, this part can be filled either by product development team or by conducting surveys or taking feedback from customers." }, { "code": null, "e": 34931, "s": 34860, "text": "Now, let’s calculate Importance Weight and Relative Importance Weight." }, { "code": null, "e": 35427, "s": 34931, "text": "Importance Weight (Color) \n= 9 * 2 + 3 * 9 + 3 * 1 = 48\n\nImportance Weight (Weight) \n= 3 * 2 = 6\n\nImportance Weight (Size) \n= 2 * 1 + 1 * 3 = 5\n\nImportance Weight (Packaging) \n= 2 * 3 + 3 * 9 + 5 * 1 = 38\n\nImportance Weight (Choice of flavor) \n= 2 * 3 + 3 * 9 + 1 * 1 + 4 * 1 + 5 * 3 = 53\n\nImportance Weight (Quantity of milk) \n= 2 * 1 + 3 * 1 + 1 * 3 + 4 * 9 + 5 * 3 = 59\n\nImportance Weight (Sugar content) \n= 3 * 9 + 5 * 9 = 72\n\nTotal Importance Weight \n= 48 + 6 + 5 + 38 + 53 + 59 + 72 \n= 281" }, { "code": null, "e": 35461, "s": 35427, "text": "Now, Relative Importance Weight :" }, { "code": null, "e": 35950, "s": 35461, "text": "Relative Importance Weight (Color) \n= ( 48 / 281 ) * 100 = 17.1\n\nRelative Importance Weight (Weight) \n= ( 6 / 281 ) * 100 = 2.14\n\nRelative Importance Weight (Size) \n= ( 5 / 281 ) * 100 = 1.78\n\nRelative Importance Weight (Packaging) \n= ( 38 / 281 ) * 100 = 13.5 \n\nRelative Importance Weight (Choice of flavor) \n= ( 53 / 281 ) * 100 = 18.86\n\nRelative Importance Weight (Quantity of milk) \n= ( 59 / 281 ) * 100 = 21.0\n\nRelative Importance Weight (Sugar content) \n= ( 72 / 281 ) * 100 = 25.6\n" }, { "code": null, "e": 36057, "s": 35950, "text": "Now, we need to fill these values in house of quality. The final house of quality diagram is shown below :" }, { "code": null, "e": 36186, "s": 36057, "text": "Note –The low level of house of quality is filled using more specific target values for product and other competitor’s products." }, { "code": null, "e": 36207, "s": 36186, "text": "Software Engineering" }, { "code": null, "e": 36305, "s": 36207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36348, "s": 36305, "text": "Software Engineering | Integration Testing" }, { "code": null, "e": 36363, "s": 36348, "text": "System Testing" }, { "code": null, "e": 36404, "s": 36363, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 36454, "s": 36404, "text": "Software Engineering | Software Quality Assurance" }, { "code": null, "e": 36486, "s": 36454, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 36525, "s": 36486, "text": "Difference between IAAS, PAAS and SAAS" }, { "code": null, "e": 36581, "s": 36525, "text": "Difference between Unit Testing and Integration Testing" }, { "code": null, "e": 36628, "s": 36581, "text": "Use Case Diagram for Library Management System" }, { "code": null, "e": 36664, "s": 36628, "text": "Object Oriented Analysis and Design" } ]
Interesting facts about Array assignment in Java - GeeksforGeeks
06 Jan, 2019 Prerequisite : Arrays in Java While working with arrays we have to do 3 tasks namely declaration, creation, initialization or Assignment.Declaration of array : int[] arr; Creation of array : // Here we create an array of size 3 int[] arr = new int[3]; Initialization of array : arr[0] = 1; arr[1] = 2; arr[3] = 3; int intArray[]; // declaring array intArray = new int[20]; // allocating memory to array Some important facts while assigning elements to the array: For primitive data types : In case of primitive type arrays, as array elements we can provide any type which can be implicitly promoted to the declared type array. Apart from that, if we are trying to use any other data-types then we will get compile-time error saying possible loss of precision.// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:108 // Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:possible loss of precision. // Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }}Output:error: incompatible types: possible lossy conversion from long to char error: incompatible types: possible lossy conversion from double to char Object type Arrays : If we are creating object type arrays then the elements of that arrays can be either declared type objects or it can be child class object.// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }}Output:10 20.5 // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }}Output:Compile-time error(incompatible types) // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = "GEEKS"; }}Output:error: incompatible types: char cannot be converted to Number error: incompatible types: String cannot be converted to Number Interface type array : For interface type array, we can assign elements as its implementation class objects.// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }}// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }}Output:Compile-time error(Incompatible types) Explanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface. For primitive data types : In case of primitive type arrays, as array elements we can provide any type which can be implicitly promoted to the declared type array. Apart from that, if we are trying to use any other data-types then we will get compile-time error saying possible loss of precision.// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:108 // Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:possible loss of precision. // Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }}Output:error: incompatible types: possible lossy conversion from long to char error: incompatible types: possible lossy conversion from double to char // Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }} Output: 108 // Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }} Output: possible loss of precision. // Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }} Output: error: incompatible types: possible lossy conversion from long to char error: incompatible types: possible lossy conversion from double to char Object type Arrays : If we are creating object type arrays then the elements of that arrays can be either declared type objects or it can be child class object.// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }}Output:10 20.5 // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }}Output:Compile-time error(incompatible types) // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = "GEEKS"; }}Output:error: incompatible types: char cannot be converted to Number error: incompatible types: String cannot be converted to Number // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }} Output: 10 20.5 // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }} Output: Compile-time error(incompatible types) // Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = "GEEKS"; }} Output: error: incompatible types: char cannot be converted to Number error: incompatible types: String cannot be converted to Number Interface type array : For interface type array, we can assign elements as its implementation class objects.// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }}// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }}Output:Compile-time error(Incompatible types) Explanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface. // Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }} // Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }} Output: Compile-time error(Incompatible types) Explanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface. Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. interesting-facts Java-Array-Programs Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26263, "s": 26235, "text": "\n06 Jan, 2019" }, { "code": null, "e": 26293, "s": 26263, "text": "Prerequisite : Arrays in Java" }, { "code": null, "e": 26423, "s": 26293, "text": "While working with arrays we have to do 3 tasks namely declaration, creation, initialization or Assignment.Declaration of array :" }, { "code": null, "e": 26434, "s": 26423, "text": "int[] arr;" }, { "code": null, "e": 26454, "s": 26434, "text": "Creation of array :" }, { "code": null, "e": 26515, "s": 26454, "text": "// Here we create an array of size 3\nint[] arr = new int[3];" }, { "code": null, "e": 26541, "s": 26515, "text": "Initialization of array :" }, { "code": null, "e": 26671, "s": 26541, "text": "arr[0] = 1;\narr[1] = 2;\narr[3] = 3;\n\nint intArray[]; // declaring array\nintArray = new int[20]; // allocating memory to array" }, { "code": null, "e": 26731, "s": 26671, "text": "Some important facts while assigning elements to the array:" }, { "code": null, "e": 30779, "s": 26731, "text": "For primitive data types : In case of primitive type arrays, as array elements we can provide any type which can be implicitly promoted to the declared type array. Apart from that, if we are trying to use any other data-types then we will get compile-time error saying possible loss of precision.// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:108\n// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:possible loss of precision.\n// Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }}Output:error: incompatible types: possible lossy conversion from long to char\nerror: incompatible types: possible lossy conversion from double to char\nObject type Arrays : If we are creating object type arrays then the elements of that arrays can be either declared type objects or it can be child class object.// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }}Output:10\n20.5\n// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }}Output:Compile-time error(incompatible types)\n// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = \"GEEKS\"; }}Output:error: incompatible types: char cannot be converted to Number\nerror: incompatible types: String cannot be converted to Number\nInterface type array : For interface type array, we can assign elements as its implementation class objects.// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }}// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }}Output:Compile-time error(Incompatible types)\nExplanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface." }, { "code": null, "e": 32371, "s": 30779, "text": "For primitive data types : In case of primitive type arrays, as array elements we can provide any type which can be implicitly promoted to the declared type array. Apart from that, if we are trying to use any other data-types then we will get compile-time error saying possible loss of precision.// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:108\n// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}Output:possible loss of precision.\n// Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }}Output:error: incompatible types: possible lossy conversion from long to char\nerror: incompatible types: possible lossy conversion from double to char\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; arr[0] = 1; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}", "e": 32693, "s": 32371, "text": null }, { "code": null, "e": 32701, "s": 32693, "text": "Output:" }, { "code": null, "e": 32706, "s": 32701, "text": "108\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on int type arraypublic class Test {public static void main(String[] args) { int[] arr = new int[3]; // Assigning long value to int type. arr[0] = 10l; arr[1] = 'a'; byte b = 10; arr[2] = b; System.out.println(arr[0] + arr[1] + arr[2]); }}", "e": 33078, "s": 32706, "text": null }, { "code": null, "e": 33086, "s": 33078, "text": "Output:" }, { "code": null, "e": 33115, "s": 33086, "text": "possible loss of precision.\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on char type arraypublic class Test {public static void main(String[] args) { char[][] arr = new char[2][2]; // Assigning long value to int type. arr[0][0] = 10l; arr[0][1] = 'a'; char b = 10; arr[1][0] = b; // Assigning double value to char type arr[1][1] = 10.6; }}", "e": 33522, "s": 33115, "text": null }, { "code": null, "e": 33530, "s": 33522, "text": "Output:" }, { "code": null, "e": 33675, "s": 33530, "text": "error: incompatible types: possible lossy conversion from long to char\nerror: incompatible types: possible lossy conversion from double to char\n" }, { "code": null, "e": 35148, "s": 33675, "text": "Object type Arrays : If we are creating object type arrays then the elements of that arrays can be either declared type objects or it can be child class object.// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }}Output:10\n20.5\n// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }}Output:Compile-time error(incompatible types)\n// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = \"GEEKS\"; }}Output:error: incompatible types: char cannot be converted to Number\nerror: incompatible types: String cannot be converted to Number\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[2]; num[0] = new Integer(10); num[1] = new Double(20.5); System.out.println(num[0]); System.out.println(num[1]); }}", "e": 35484, "s": 35148, "text": null }, { "code": null, "e": 35492, "s": 35484, "text": "Output:" }, { "code": null, "e": 35501, "s": 35492, "text": "10\n20.5\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[] num = new Number[3]; num[0] = new Integer(10); num[1] = new Double(20.5); // Here String is not the child class of Number class. num[2] = new String(“GFG”); }}", "e": 35866, "s": 35501, "text": null }, { "code": null, "e": 35874, "s": 35866, "text": "Output:" }, { "code": null, "e": 35914, "s": 35874, "text": "Compile-time error(incompatible types)\n" }, { "code": "// Java program to illustrate the concept of array// element assignments on Number type arraypublic class Test {public static void main(String[] args) { Number[][] arr = new Number[2][2]; arr[0][0] = 10l; // Assigning char to Number type array arr[0][1] = 'a'; byte b = 10; arr[1][0] = b; // Assigning String to Number type array arr[1][1] = \"GEEKS\"; }}", "e": 36334, "s": 35914, "text": null }, { "code": null, "e": 36342, "s": 36334, "text": "Output:" }, { "code": null, "e": 36469, "s": 36342, "text": "error: incompatible types: char cannot be converted to Number\nerror: incompatible types: String cannot be converted to Number\n" }, { "code": null, "e": 37454, "s": 36469, "text": "Interface type array : For interface type array, we can assign elements as its implementation class objects.// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }}// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }}Output:Compile-time error(Incompatible types)\nExplanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface." }, { "code": "// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; // Thread class implements Runnable interface. run[0] = new Thread(); run[1] = new Thread(); }}", "e": 37776, "s": 37454, "text": null }, { "code": "// Java program to illustrate the concept of array// element assignments on Interface type arraypublic class Test {public static void main(String[] args) { Runnable[] run = new Runnable[2]; run[0] = new Thread(); // String class does not implements Runnable interface. run[1] = new String(“GFG”); }}", "e": 38112, "s": 37776, "text": null }, { "code": null, "e": 38120, "s": 38112, "text": "Output:" }, { "code": null, "e": 38160, "s": 38120, "text": "Compile-time error(Incompatible types)\n" }, { "code": null, "e": 38335, "s": 38160, "text": "Explanation: In the above program, we are giving elements of String class that’s cause compile time error. Because we know that String does not implements Runnable interface." }, { "code": null, "e": 38409, "s": 38335, "text": "Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html" }, { "code": null, "e": 38715, "s": 38409, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 38840, "s": 38715, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 38858, "s": 38840, "text": "interesting-facts" }, { "code": null, "e": 38878, "s": 38858, "text": "Java-Array-Programs" }, { "code": null, "e": 38890, "s": 38878, "text": "Java-Arrays" }, { "code": null, "e": 38895, "s": 38890, "text": "Java" }, { "code": null, "e": 38900, "s": 38895, "text": "Java" }, { "code": null, "e": 38998, "s": 38900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39049, "s": 38998, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 39079, "s": 39049, "text": "HashMap in Java with Examples" }, { "code": null, "e": 39094, "s": 39079, "text": "Stream In Java" }, { "code": null, "e": 39113, "s": 39094, "text": "Interfaces in Java" }, { "code": null, "e": 39144, "s": 39113, "text": "How to iterate any Map in Java" }, { "code": null, "e": 39162, "s": 39144, "text": "ArrayList in Java" }, { "code": null, "e": 39194, "s": 39162, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 39214, "s": 39194, "text": "Stack Class in Java" }, { "code": null, "e": 39238, "s": 39214, "text": "Singleton Class in Java" } ]
numpy.not_equal() in Python - GeeksforGeeks
28 Mar, 2022 The numpy.not_equal() checks whether two element or unequal or not. Syntax : numpy.not_equal(x1, x2[, out]) Parameters : x1, x2 : [array_like]Input Array whose elements we want to check out : [ndarray, optional]Output array that returns True/False. A placeholder the same shape as x1 to store the result. Return : Boolean array Code 1 : Python # Python Program illustrating# numpy.not_equal() method import numpy as geek a = geek.not_equal([1., 2.], [1., 3.])print("Not equal : \n", a, "\n") b = geek.not_equal([1, 2], [[1, 3],[1, 4]])print("Not equal : \n", b, "\n") Output : Not equal : [False True] Not equal : [[False True] [False True]] Code 2 : Python # Python Program illustrating# numpy.not_equal() method import numpy as geek # Here we will compare Complex values with inta = geek.array([0 + 1j, 2])b = geek.array([1,2]) d = geek.not_equal(a, b)print("Comparing complex with int using .not_equal() : ", d) Output : Comparing complex with int using .not_equal() : [ True False] Code 3 : Python # Python Program illustrating# numpy.not_equal() method import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2]) d = geek.not_equal(a, b)print("\nComparing float with int using .not_equal() : ", d) Output : Comparing float with int using .not_equal() : [ True True] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.not_equal.html Note :These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using 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. nidhi_biet vinayedula Python numpy-Logic Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25615, "s": 25537, "text": "The numpy.not_equal() checks whether two element or unequal or not. Syntax : " }, { "code": null, "e": 25646, "s": 25615, "text": "numpy.not_equal(x1, x2[, out])" }, { "code": null, "e": 25660, "s": 25646, "text": "Parameters : " }, { "code": null, "e": 25851, "s": 25660, "text": "x1, x2 : [array_like]Input Array whose elements we want to check\nout : [ndarray, optional]Output array that returns True/False.\n A placeholder the same shape as x1 to store the result." }, { "code": null, "e": 25861, "s": 25851, "text": "Return : " }, { "code": null, "e": 25876, "s": 25861, "text": "Boolean array " }, { "code": null, "e": 25886, "s": 25876, "text": "Code 1 : " }, { "code": null, "e": 25893, "s": 25886, "text": "Python" }, { "code": "# Python Program illustrating# numpy.not_equal() method import numpy as geek a = geek.not_equal([1., 2.], [1., 3.])print(\"Not equal : \\n\", a, \"\\n\") b = geek.not_equal([1, 2], [[1, 3],[1, 4]])print(\"Not equal : \\n\", b, \"\\n\")", "e": 26119, "s": 25893, "text": null }, { "code": null, "e": 26129, "s": 26119, "text": "Output : " }, { "code": null, "e": 26205, "s": 26129, "text": "Not equal : \n [False True] \n\nNot equal : \n [[False True]\n [False True]] " }, { "code": null, "e": 26215, "s": 26205, "text": "Code 2 : " }, { "code": null, "e": 26222, "s": 26215, "text": "Python" }, { "code": "# Python Program illustrating# numpy.not_equal() method import numpy as geek # Here we will compare Complex values with inta = geek.array([0 + 1j, 2])b = geek.array([1,2]) d = geek.not_equal(a, b)print(\"Comparing complex with int using .not_equal() : \", d)", "e": 26482, "s": 26222, "text": null }, { "code": null, "e": 26492, "s": 26482, "text": "Output : " }, { "code": null, "e": 26555, "s": 26492, "text": "Comparing complex with int using .not_equal() : [ True False]" }, { "code": null, "e": 26565, "s": 26555, "text": "Code 3 : " }, { "code": null, "e": 26572, "s": 26565, "text": "Python" }, { "code": "# Python Program illustrating# numpy.not_equal() method import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2]) d = geek.not_equal(a, b)print(\"\\nComparing float with int using .not_equal() : \", d)", "e": 26829, "s": 26572, "text": null }, { "code": null, "e": 26839, "s": 26829, "text": "Output : " }, { "code": null, "e": 26901, "s": 26839, "text": " Comparing float with int using .not_equal() : [ True True]" }, { "code": null, "e": 27522, "s": 26901, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.not_equal.html Note :These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using 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": 27533, "s": 27522, "text": "nidhi_biet" }, { "code": null, "e": 27544, "s": 27533, "text": "vinayedula" }, { "code": null, "e": 27573, "s": 27544, "text": "Python numpy-Logic Functions" }, { "code": null, "e": 27586, "s": 27573, "text": "Python-numpy" }, { "code": null, "e": 27593, "s": 27586, "text": "Python" }, { "code": null, "e": 27691, "s": 27593, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27723, "s": 27691, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27765, "s": 27723, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27807, "s": 27765, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27863, "s": 27807, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27890, "s": 27863, "text": "Python Classes and Objects" }, { "code": null, "e": 27929, "s": 27890, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27960, "s": 27929, "text": "Python | os.path.join() method" }, { "code": null, "e": 27982, "s": 27960, "text": "Defaultdict in Python" }, { "code": null, "e": 28011, "s": 27982, "text": "Create a directory in Python" } ]
Lexical analysis - GeeksforGeeks
21 Jan, 2014 printf ( "i = %d, &i = %x" , i , & i ) ; Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? How to calculate MOVING AVERAGE in a Pandas DataFrame? Find size of largest subset with bitwise AND greater than their bitwise XOR What is Transmission Control Protocol (TCP)? Python OpenCV - Canny() Function How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python
[ { "code": null, "e": 26463, "s": 26435, "text": "\n21 Jan, 2014" }, { "code": null, "e": 26505, "s": 26463, "text": "printf\n(\n\"i = %d, &i = %x\"\n, \ni\n,\n&\ni\n)\n;" }, { "code": null, "e": 26603, "s": 26505, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 26635, "s": 26603, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 26688, "s": 26635, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 26754, "s": 26688, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 26809, "s": 26754, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 26885, "s": 26809, "text": "Find size of largest subset with bitwise AND greater than their bitwise XOR" }, { "code": null, "e": 26930, "s": 26885, "text": "What is Transmission Control Protocol (TCP)?" }, { "code": null, "e": 26963, "s": 26930, "text": "Python OpenCV - Canny() Function" }, { "code": null, "e": 27021, "s": 26963, "text": "How to Convert Categorical Variable to Numeric in Pandas?" }, { "code": null, "e": 27083, "s": 27021, "text": "How to Replace Values in Column Based on Condition in Pandas?" } ]
Number of single cycle components in an undirected graph - 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 TutorialsAlgorithmsAnalysis 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 ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers 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 ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems 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 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 Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet 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 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 Student Chapter Geek on the Top Internship Careers Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Student Chapter Geek on the Top Internship Careers Curated DSA Lists Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Top 50 Array Problems Top 50 String Problems Top 50 Tree Problems Top 50 Graph Problems Top 50 DP Problems Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON Practice All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet All DSA Problems Problem of the Day Interview Series: Weekly Contests Bi-Wizard Coding: School Contests Contests and Events Practice SDE Sheet 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 Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Graph and its representations Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Detect Cycle in a Directed Graph Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Detect cycle in an undirected graph Strongly Connected Components Find the number of islands | Set 1 (Using DFS) Minimum number of swaps required to sort an array Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Ford-Fulkerson Algorithm for Maximum Flow Problem Check whether a given graph is Bipartite or not Shortest path in an unweighted graph Iterative Depth First Traversal of Graph Traveling Salesman Problem (TSP) Implementation Connected Components in an undirected graph Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Print all paths from a given source to a destination Applications of Depth First Search m Coloring Problem | Backtracking-5 Dijkstra's Shortest Path Algorithm using priority_queue of STL Hamiltonian Cycle | Backtracking-6 Kahn's algorithm for Topological Sorting Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Graph and its representations Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Detect Cycle in a Directed Graph Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Detect cycle in an undirected graph Strongly Connected Components Find the number of islands | Set 1 (Using DFS) Minimum number of swaps required to sort an array Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Ford-Fulkerson Algorithm for Maximum Flow Problem Check whether a given graph is Bipartite or not Shortest path in an unweighted graph Iterative Depth First Traversal of Graph Traveling Salesman Problem (TSP) Implementation Connected Components in an undirected graph Union-Find Algorithm | Set 2 (Union By Rank and Path Compression) Print all paths from a given source to a destination Applications of Depth First Search m Coloring Problem | Backtracking-5 Dijkstra's Shortest Path Algorithm using priority_queue of STL Hamiltonian Cycle | Backtracking-6 Kahn's algorithm for Topological Sorting Difficulty Level : Medium Given a set of ‘n’ vertices and ‘m’ edges of an undirected simple graph (no parallel edges and no self-loop), find the number of single-cycle-components present in the graph. A single-cyclic-component is a graph of n nodes containing a single cycle through all nodes of the component.Example: Let us consider the following graph with 15 vertices. Input: V = 15, E = 14 1 10 // edge 1 1 5 // edge 2 5 10 // edge 3 2 9 // .. 9 15 // .. 2 15 // .. 2 12 // .. 12 15 // .. 13 8 // .. 6 14 // .. 14 3 // .. 3 7 // .. 7 11 // edge 13 11 6 // edge 14 Output :2 In the above-mentioned example, the two single-cyclic-components are composed of vertices (1, 10, 5) and (6, 11, 7, 3, 14) respectively. Now we can easily see that a single-cycle-component is a connected component where every vertex has the degree as two. Therefore, in order to solve this problem we first identify all the connected components of the disconnected graph. For this, we use depth-first search algorithm. For the DFS algorithm to work, it is required to maintain an array ‘found’ to keep an account of all the vertices that have been discovered by the recursive function DFS. Once all the elements of a particular connected component are discovered (like vertices(9, 2, 15, 12) form a connected graph component ), we check if all the vertices in the component are having the degree equal to two. If yes, we increase the counter variable ‘count’ which denotes the number of single-cycle-components found in the given graph. To keep an account of the component we are presently dealing with, we may use a vector array ‘curr_graph’ as well. C++ Java Python3 C# Javascript // CPP program to find single cycle components// in a graph.#include <bits/stdc++.h>using namespace std; const int N = 100000; // degree of all the verticesint degree[N]; // to keep track of all the vertices covered// till nowbool found[N]; // all the vertices in a particular// connected component of the graphvector<int> curr_graph; // adjacency listvector<int> adj_list[N]; // depth-first traversal to identify all the// nodes in a particular connected graph// componentvoid DFS(int v){ found[v] = true; curr_graph.push_back(v); for (int it : adj_list[v]) if (!found[it]) DFS(it);} // function to add an edge in the graphvoid addEdge(vector<int> adj_list[N], int src, int dest){ // for index decrement both src and dest. src--, dest--; adj_list[src].push_back(dest); adj_list[dest].push_back(src); degree[src]++; degree[dest]++;} int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v : curr_graph) { if (degree[v] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} int main(){ // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge(adj_list, 1, 10); addEdge(adj_list, 1, 5); addEdge(adj_list, 5, 10); addEdge(adj_list, 2, 9); addEdge(adj_list, 9, 15); addEdge(adj_list, 2, 15); addEdge(adj_list, 2, 12); addEdge(adj_list, 12, 15); addEdge(adj_list, 13, 8); addEdge(adj_list, 6, 14); addEdge(adj_list, 14, 3); addEdge(adj_list, 3, 7); addEdge(adj_list, 7, 11); addEdge(adj_list, 11, 6); cout << countSingleCycles(n, m); return 0;} // Java program to find single cycle components// in a graph.import java.util.*; class GFG{ static int N = 100000; // degree of all the verticesstatic int degree[] = new int[N]; // to keep track of all the vertices covered// till nowstatic boolean found[] = new boolean[N]; // all the vertices in a particular// connected component of the graphstatic Vector<Integer> curr_graph = new Vector<Integer>(); // adjacency liststatic Vector<Vector<Integer>> adj_list = new Vector<Vector<Integer>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){ found[v] = true; curr_graph.add(v); for (int it = 0 ;it < adj_list.get(v).size(); it++) if (!found[adj_list.get(v).get(it)]) DFS(adj_list.get(v).get(it));} // function to add an edge in the graphstatic void addEdge( int src,int dest){ // for index decrement both src and dest. src--; dest--; adj_list.get(src).add(dest); adj_list.get(dest).add(src); degree[src]++; degree[dest]++;} static int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v = 0 ; v < curr_graph.size(); v++) { if (degree[curr_graph.get(v)] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codepublic static void main(String args[]){ for(int i = 0; i < N + 1; i++) adj_list.add(new Vector<Integer>()); // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge( 1, 10); addEdge( 1, 5); addEdge( 5, 10); addEdge( 2, 9); addEdge( 9, 15); addEdge( 2, 15); addEdge( 2, 12); addEdge( 12, 15); addEdge( 13, 8); addEdge( 6, 14); addEdge( 14, 3); addEdge( 3, 7); addEdge( 7, 11); addEdge( 11, 6); System.out.println(countSingleCycles(n, m));}} // This code is contributed by Arnab Kundu # Python3 program to find single# cycle components in a graph.N = 100000 # degree of all the verticesdegree = [0] * N # to keep track of all the# vertices covered till nowfound = [None] * N # All the vertices in a particular# connected component of the graphcurr_graph = [] # adjacency listadj_list = [[] for i in range(N)] # depth-first traversal to identify# all the nodes in a particular# connected graph componentdef DFS(v): found[v] = True curr_graph.append(v) for it in adj_list[v]: if not found[it]: DFS(it) # function to add an edge in the graphdef addEdge(adj_list, src, dest): # for index decrement both src and dest. src, dest = src - 1, dest - 1 adj_list[src].append(dest) adj_list[dest].append(src) degree[src] += 1 degree[dest] += 1 def countSingleCycles(n, m): # count of cycle graph components count = 0 for i in range(0, n): if not found[i]: curr_graph.clear() DFS(i) # traversing the nodes of the # current graph component flag = 1 for v in curr_graph: if degree[v] == 2: continue else: flag = 0 break if flag == 1: count += 1 return count # Driver Codeif __name__ == "__main__": # n->number of vertices # m->number of edges n, m = 15, 14 addEdge(adj_list, 1, 10) addEdge(adj_list, 1, 5) addEdge(adj_list, 5, 10) addEdge(adj_list, 2, 9) addEdge(adj_list, 9, 15) addEdge(adj_list, 2, 15) addEdge(adj_list, 2, 12) addEdge(adj_list, 12, 15) addEdge(adj_list, 13, 8) addEdge(adj_list, 6, 14) addEdge(adj_list, 14, 3) addEdge(adj_list, 3, 7) addEdge(adj_list, 7, 11) addEdge(adj_list, 11, 6) print(countSingleCycles(n, m)) # This code is contributed by Rituraj Jain // C# program to find single cycle components// in a graph.using System;using System.Collections.Generic; class GFG{static int N = 100000; // degree of all the verticesstatic int []degree = new int[N]; // to keep track of all the vertices covered// till nowstatic bool []found = new bool[N]; // all the vertices in a particular// connected component of the graphstatic List<int> curr_graph = new List<int>(); // adjacency liststatic List<List<int>> adj_list = new List<List<int>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){ found[v] = true; curr_graph.Add(v); for (int it = 0; it < adj_list[v].Count; it++) if (!found[adj_list[v][it]]) DFS(adj_list[v][it]);} // function to add an edge in the graphstatic void addEdge(int src,int dest){ // for index decrement both src and dest. src--; dest--; adj_list[src].Add(dest); adj_list[dest].Add(src); degree[src]++; degree[dest]++;} static int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.Clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v = 0 ; v < curr_graph.Count; v++) { if (degree[curr_graph[v]] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codepublic static void Main(String []args){ for(int i = 0; i < N + 1; i++) adj_list.Add(new List<int>()); // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge(1, 10); addEdge(1, 5); addEdge(5, 10); addEdge(2, 9); addEdge(9, 15); addEdge(2, 15); addEdge(2, 12); addEdge(12, 15); addEdge(13, 8); addEdge(6, 14); addEdge(14, 3); addEdge(3, 7); addEdge(7, 11); addEdge(11, 6); Console.WriteLine(countSingleCycles(n, m));}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to find single cycle components// in a graph. let N = 100000; // degree of all the verticeslet degree=new Array(N);for(let i=0;i<N;i++) degree[i]=0;// to keep track of all the vertices covered// till nowlet found=new Array(N);for(let i=0;i<N;i++) found[i]=0; // all the vertices in a particular// connected component of the graphlet curr_graph = []; // adjacency listlet adj_list = []; // depth-first traversal to identify all the// nodes in a particular connected graph// componentfunction DFS(v){ found[v] = true; curr_graph.push(v); for (let it = 0 ;it < adj_list[v].length; it++) if (!found[adj_list[v][it]]) DFS(adj_list[v][it]);} // function to add an edge in the graphfunction addEdge(src,dest){ // for index decrement both src and dest. src--; dest--; adj_list[src].push(dest); adj_list[dest].push(src); degree[src]++; degree[dest]++;} function countSingleCycles(n,m){ // count of cycle graph components let count = 0; for (let i = 0; i < n; ++i) { if (!found[i]) { curr_graph=[]; DFS(i); // traversing the nodes of the // current graph component let flag = 1; for (let v = 0 ; v < curr_graph.length; v++) { if (degree[curr_graph[v]] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codefor(let i = 0; i < N + 1; i++) adj_list.push([]); // n->number of vertices// m->number of edgeslet n = 15, m = 14;addEdge( 1, 10);addEdge( 1, 5);addEdge( 5, 10);addEdge( 2, 9);addEdge( 9, 15);addEdge( 2, 15);addEdge( 2, 12);addEdge( 12, 15);addEdge( 13, 8);addEdge( 6, 14);addEdge( 14, 3);addEdge( 3, 7);addEdge( 7, 11);addEdge( 11, 6); document.write(countSingleCycles(n, m)); // This code is contributed by avanitrachhadiya2155 </script> 2 Hence, total number of cycle graph component is found. PiyushKumar rituraj_jain andrew1234 princiraj1992 avanitrachhadiya2155 DFS graph-connectivity graph-cycle Graph Greedy Greedy DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Longest Path in a Directed Acyclic Graph Best First Search (Informed Search) Graph Coloring | Set 2 (Greedy Algorithm) Maximum Bipartite Matching Graph Coloring | Set 1 (Introduction and Applications) Program for array rotation Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1
[ { "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": 3985, "s": 1469, "text": "TutorialsAlgorithmsAnalysis 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 ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 4566, "s": 3985, "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": 4899, "s": 4566, "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": 4919, "s": 4899, "text": "Asymptotic Analysis" }, { "code": null, "e": 4949, "s": 4919, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 4970, "s": 4949, "text": "Asymptotic Notations" }, { "code": null, "e": 5006, "s": 4970, "text": "Little o and little omega notations" }, { "code": null, "e": 5035, "s": 5006, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5053, "s": 5035, "text": "Analysis of Loops" }, { "code": null, "e": 5073, "s": 5053, "text": "Solving Recurrences" }, { "code": null, "e": 5092, "s": 5073, "text": "Amortized Analysis" }, { "code": null, "e": 5128, "s": 5092, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5157, "s": 5128, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5194, "s": 5157, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5221, "s": 5194, "text": "A Time Complexity Question" }, { "code": null, "e": 5242, "s": 5221, "text": "Searching Algorithms" }, { "code": null, "e": 5261, "s": 5242, "text": "Sorting Algorithms" }, { "code": null, "e": 5278, "s": 5261, "text": "Graph Algorithms" }, { "code": null, "e": 5296, "s": 5278, "text": "Pattern Searching" }, { "code": null, "e": 5317, "s": 5296, "text": "Geometric Algorithms" }, { "code": null, "e": 5330, "s": 5317, "text": "Mathematical" }, { "code": null, "e": 5349, "s": 5330, "text": "Bitwise Algorithms" }, { "code": null, "e": 5371, "s": 5349, "text": "Randomized Algorithms" }, { "code": null, "e": 5389, "s": 5371, "text": "Greedy Algorithms" }, { "code": null, "e": 5409, "s": 5389, "text": "Dynamic Programming" }, { "code": null, "e": 5428, "s": 5409, "text": "Divide and Conquer" }, { "code": null, "e": 5441, "s": 5428, "text": "Backtracking" }, { "code": null, "e": 5458, "s": 5441, "text": "Branch and Bound" }, { "code": null, "e": 5473, "s": 5458, "text": "All Algorithms" }, { "code": null, "e": 5616, "s": 5473, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5623, "s": 5616, "text": "Arrays" }, { "code": null, "e": 5635, "s": 5623, "text": "Linked List" }, { "code": null, "e": 5641, "s": 5635, "text": "Stack" }, { "code": null, "e": 5647, "s": 5641, "text": "Queue" }, { "code": null, "e": 5659, "s": 5647, "text": "Binary Tree" }, { "code": null, "e": 5678, "s": 5659, "text": "Binary Search Tree" }, { "code": null, "e": 5683, "s": 5678, "text": "Heap" }, { "code": null, "e": 5691, "s": 5683, "text": "Hashing" }, { "code": null, "e": 5697, "s": 5691, "text": "Graph" }, { "code": null, "e": 5721, "s": 5697, "text": "Advanced Data Structure" }, { "code": null, "e": 5728, "s": 5721, "text": "Matrix" }, { "code": null, "e": 5736, "s": 5728, "text": "Strings" }, { "code": null, "e": 5756, "s": 5736, "text": "All Data Structures" }, { "code": null, "e": 5976, "s": 5756, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 5996, "s": 5976, "text": "Company Preparation" }, { "code": null, "e": 6007, "s": 5996, "text": "Top Topics" }, { "code": null, "e": 6034, "s": 6007, "text": "Practice Company Questions" }, { "code": null, "e": 6056, "s": 6034, "text": "Interview Experiences" }, { "code": null, "e": 6079, "s": 6056, "text": "Experienced Interviews" }, { "code": null, "e": 6101, "s": 6079, "text": "Internship Interviews" }, { "code": null, "e": 6126, "s": 6101, "text": "Competititve Programming" }, { "code": null, "e": 6142, "s": 6126, "text": "Design Patterns" }, { "code": null, "e": 6165, "s": 6142, "text": "System Design Tutorial" }, { "code": null, "e": 6189, "s": 6165, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6270, "s": 6189, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6272, "s": 6270, "text": "C" }, { "code": null, "e": 6276, "s": 6272, "text": "C++" }, { "code": null, "e": 6281, "s": 6276, "text": "Java" }, { "code": null, "e": 6288, "s": 6281, "text": "Python" }, { "code": null, "e": 6291, "s": 6288, "text": "C#" }, { "code": null, "e": 6302, "s": 6291, "text": "JavaScript" }, { "code": null, "e": 6309, "s": 6302, "text": "jQuery" }, { "code": null, "e": 6313, "s": 6309, "text": "SQL" }, { "code": null, "e": 6317, "s": 6313, "text": "PHP" }, { "code": null, "e": 6323, "s": 6317, "text": "Scala" }, { "code": null, "e": 6328, "s": 6323, "text": "Perl" }, { "code": null, "e": 6340, "s": 6328, "text": "Go Language" }, { "code": null, "e": 6345, "s": 6340, "text": "HTML" }, { "code": null, "e": 6349, "s": 6345, "text": "CSS" }, { "code": null, "e": 6356, "s": 6349, "text": "Kotlin" }, { "code": null, "e": 6402, "s": 6356, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6419, "s": 6402, "text": "Machine Learning" }, { "code": null, "e": 6432, "s": 6419, "text": "Data Science" }, { "code": null, "e": 6599, "s": 6432, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6611, "s": 6599, "text": "Mathematics" }, { "code": null, "e": 6628, "s": 6611, "text": "Operating System" }, { "code": null, "e": 6633, "s": 6628, "text": "DBMS" }, { "code": null, "e": 6651, "s": 6633, "text": "Computer Networks" }, { "code": null, "e": 6690, "s": 6651, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6712, "s": 6690, "text": "Theory of Computation" }, { "code": null, "e": 6728, "s": 6712, "text": "Compiler Design" }, { "code": null, "e": 6742, "s": 6728, "text": "Digital Logic" }, { "code": null, "e": 6763, "s": 6742, "text": "Software Engineering" }, { "code": null, "e": 6938, "s": 6763, "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": 6966, "s": 6938, "text": "GATE Computer Science Notes" }, { "code": null, "e": 6984, "s": 6966, "text": "Last Minute Notes" }, { "code": null, "e": 7006, "s": 6984, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7048, "s": 7006, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7064, "s": 7048, "text": "GATE 2021 Dates" }, { "code": null, "e": 7086, "s": 7064, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7115, "s": 7086, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7189, "s": 7115, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7194, "s": 7189, "text": "HTML" }, { "code": null, "e": 7198, "s": 7194, "text": "CSS" }, { "code": null, "e": 7209, "s": 7198, "text": "JavaScript" }, { "code": null, "e": 7219, "s": 7209, "text": "AngularJS" }, { "code": null, "e": 7227, "s": 7219, "text": "ReactJS" }, { "code": null, "e": 7234, "s": 7227, "text": "NodeJS" }, { "code": null, "e": 7244, "s": 7234, "text": "Bootstrap" }, { "code": null, "e": 7251, "s": 7244, "text": "jQuery" }, { "code": null, "e": 7255, "s": 7251, "text": "PHP" }, { "code": null, "e": 7318, "s": 7255, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7343, "s": 7318, "text": "Software Design Patterns" }, { "code": null, "e": 7366, "s": 7343, "text": "System Design Tutorial" }, { "code": null, "e": 7923, "s": 7366, "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": 7942, "s": 7923, "text": "School Programming" }, { "code": null, "e": 8034, "s": 7942, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8048, "s": 8034, "text": "Number System" }, { "code": null, "e": 8056, "s": 8048, "text": "Algebra" }, { "code": null, "e": 8069, "s": 8056, "text": "Trigonometry" }, { "code": null, "e": 8080, "s": 8069, "text": "Statistics" }, { "code": null, "e": 8092, "s": 8080, "text": "Probability" }, { "code": null, "e": 8101, "s": 8092, "text": "Geometry" }, { "code": null, "e": 8113, "s": 8101, "text": "Mensuration" }, { "code": null, "e": 8122, "s": 8113, "text": "Calculus" }, { "code": null, "e": 8215, "s": 8122, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8229, "s": 8215, "text": "Class 8 Notes" }, { "code": null, "e": 8243, "s": 8229, "text": "Class 9 Notes" }, { "code": null, "e": 8258, "s": 8243, "text": "Class 10 Notes" }, { "code": null, "e": 8273, "s": 8258, "text": "Class 11 Notes" }, { "code": null, "e": 8288, "s": 8273, "text": "Class 12 Notes" }, { "code": null, "e": 8417, "s": 8288, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8440, "s": 8417, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8463, "s": 8440, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8487, "s": 8463, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8511, "s": 8487, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8535, "s": 8511, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8668, "s": 8535, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8691, "s": 8668, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8714, "s": 8691, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8738, "s": 8714, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8762, "s": 8738, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8786, "s": 8762, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8867, "s": 8786, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8881, "s": 8867, "text": "Class 8 Notes" }, { "code": null, "e": 8895, "s": 8881, "text": "Class 9 Notes" }, { "code": null, "e": 8910, "s": 8895, "text": "Class 10 Notes" }, { "code": null, "e": 8925, "s": 8910, "text": "Class 11 Notes" }, { "code": null, "e": 9131, "s": 8925, "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": 9242, "s": 9131, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9284, "s": 9242, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9306, "s": 9284, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9351, "s": 9306, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9434, "s": 9351, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9460, "s": 9434, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9487, "s": 9460, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9512, "s": 9487, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9717, "s": 9512, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers" }, { "code": null, "e": 9743, "s": 9717, "text": "Campus Ambassador Program" }, { "code": null, "e": 9769, "s": 9743, "text": "School Ambassador Program" }, { "code": null, "e": 9777, "s": 9769, "text": "Project" }, { "code": null, "e": 9795, "s": 9777, "text": "Geek of the Month" }, { "code": null, "e": 9820, "s": 9795, "text": "Campus Geek of the Month" }, { "code": null, "e": 9837, "s": 9820, "text": "Placement Course" }, { "code": null, "e": 9862, "s": 9837, "text": "Competititve Programming" }, { "code": null, "e": 9875, "s": 9862, "text": "Testimonials" }, { "code": null, "e": 9891, "s": 9875, "text": "Student Chapter" }, { "code": null, "e": 9907, "s": 9891, "text": "Geek on the Top" }, { "code": null, "e": 9918, "s": 9907, "text": "Internship" }, { "code": null, "e": 9926, "s": 9918, "text": "Careers" }, { "code": null, "e": 9965, "s": 9926, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 9980, "s": 9965, "text": "Apply for Jobs" }, { "code": null, "e": 9991, "s": 9980, "text": "Post a Job" }, { "code": null, "e": 10002, "s": 9991, "text": "JOB-A-THON" }, { "code": null, "e": 10267, "s": 10002, "text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10284, "s": 10267, "text": "All DSA Problems" }, { "code": null, "e": 10303, "s": 10284, "text": "Problem of the Day" }, { "code": null, "e": 10337, "s": 10303, "text": "Interview Series: Weekly Contests" }, { "code": null, "e": 10371, "s": 10337, "text": "Bi-Wizard Coding: School Contests" }, { "code": null, "e": 10391, "s": 10371, "text": "Contests and Events" }, { "code": null, "e": 10410, "s": 10391, "text": "Practice SDE Sheet" }, { "code": null, "e": 10530, "s": 10410, "text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems" }, { "code": null, "e": 10552, "s": 10530, "text": "Top 50 Array Problems" }, { "code": null, "e": 10575, "s": 10552, "text": "Top 50 String Problems" }, { "code": null, "e": 10596, "s": 10575, "text": "Top 50 Tree Problems" }, { "code": null, "e": 10618, "s": 10596, "text": "Top 50 Graph Problems" }, { "code": null, "e": 10637, "s": 10618, "text": "Top 50 DP Problems" }, { "code": null, "e": 10908, "s": 10641, "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": 10921, "s": 10908, "text": "Geeks Digest" }, { "code": null, "e": 10929, "s": 10921, "text": "Quizzes" }, { "code": null, "e": 10942, "s": 10929, "text": "Geeks Campus" }, { "code": null, "e": 10957, "s": 10942, "text": "Gblog Articles" }, { "code": null, "e": 10961, "s": 10957, "text": "IDE" }, { "code": null, "e": 10975, "s": 10961, "text": "Campus Mantri" }, { "code": null, "e": 10983, "s": 10975, "text": "Sign In" }, { "code": null, "e": 10991, "s": 10983, "text": "Sign In" }, { "code": null, "e": 10996, "s": 10991, "text": "Home" }, { "code": null, "e": 11009, "s": 10996, "text": "Saved Videos" }, { "code": null, "e": 11017, "s": 11009, "text": "Courses" }, { "code": null, "e": 15482, "s": 11017, "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\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\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 15536, "s": 15482, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 15659, "s": 15536, "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": 15678, "s": 15659, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 15694, "s": 15678, "text": "\nSystem Design\n" }, { "code": null, "e": 15721, "s": 15694, "text": "\nJava Backend Development\n" }, { "code": null, "e": 15739, "s": 15721, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 15754, "s": 15739, "text": "\nExplore More\n" }, { "code": null, "e": 15862, "s": 15754, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15880, "s": 15862, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15893, "s": 15880, "text": "\nSDE Theory\n" }, { "code": null, "e": 15920, "s": 15893, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15935, "s": 15920, "text": "\nExplore More\n" }, { "code": null, "e": 15976, "s": 15935, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 16088, "s": 15976, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 16114, "s": 16088, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 16141, "s": 16114, "text": "\nData Structures with C++\n" }, { "code": null, "e": 16156, "s": 16141, "text": "\nData Science\n" }, { "code": null, "e": 16171, "s": 16156, "text": "\nExplore More\n" }, { "code": null, "e": 16267, "s": 16171, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 16285, "s": 16267, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 16291, "s": 16285, "text": "\nCIP\n" }, { "code": null, "e": 16313, "s": 16291, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 16328, "s": 16313, "text": "\nExplore More\n" }, { "code": null, "e": 16439, "s": 16328, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n" }, { "code": null, "e": 16454, "s": 16439, "text": "\nSchool Guide\n" }, { "code": null, "e": 16475, "s": 16454, "text": "\nPython Programming\n" }, { "code": null, "e": 16496, "s": 16475, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 16511, "s": 16496, "text": "\nExplore more\n" }, { "code": null, "e": 16816, "s": 16511, "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": 16839, "s": 16816, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16860, "s": 16839, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16879, "s": 16860, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16899, "s": 16879, "text": "\nPattern Searching\n" }, { "code": null, "e": 16922, "s": 16899, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16937, "s": 16922, "text": "\nMathematical\n" }, { "code": null, "e": 16958, "s": 16937, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16982, "s": 16958, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 17002, "s": 16982, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 17024, "s": 17002, "text": "\nDynamic Programming\n" }, { "code": null, "e": 17045, "s": 17024, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 17060, "s": 17045, "text": "\nBacktracking\n" }, { "code": null, "e": 17079, "s": 17060, "text": "\nBranch and Bound\n" }, { "code": null, "e": 17096, "s": 17079, "text": "\nAll Algorithms\n" }, { "code": null, "e": 17481, "s": 17096, "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": 17503, "s": 17481, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 17535, "s": 17503, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 17558, "s": 17535, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 17596, "s": 17558, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 17627, "s": 17596, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 17647, "s": 17627, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 17669, "s": 17647, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17690, "s": 17669, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17728, "s": 17690, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17759, "s": 17728, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17798, "s": 17759, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17827, "s": 17798, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 18024, "s": 17827, "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": 18033, "s": 18024, "text": "\nArrays\n" }, { "code": null, "e": 18047, "s": 18033, "text": "\nLinked List\n" }, { "code": null, "e": 18055, "s": 18047, "text": "\nStack\n" }, { "code": null, "e": 18063, "s": 18055, "text": "\nQueue\n" }, { "code": null, "e": 18077, "s": 18063, "text": "\nBinary Tree\n" }, { "code": null, "e": 18098, "s": 18077, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 18105, "s": 18098, "text": "\nHeap\n" }, { "code": null, "e": 18115, "s": 18105, "text": "\nHashing\n" }, { "code": null, "e": 18123, "s": 18115, "text": "\nGraph\n" }, { "code": null, "e": 18149, "s": 18123, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 18158, "s": 18149, "text": "\nMatrix\n" }, { "code": null, "e": 18168, "s": 18158, "text": "\nStrings\n" }, { "code": null, "e": 18190, "s": 18168, "text": "\nAll Data Structures\n" }, { "code": null, "e": 18458, "s": 18190, "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": 18480, "s": 18458, "text": "\nCompany Preparation\n" }, { "code": null, "e": 18493, "s": 18480, "text": "\nTop Topics\n" }, { "code": null, "e": 18522, "s": 18493, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 18546, "s": 18522, "text": "\nInterview Experiences\n" }, { "code": null, "e": 18571, "s": 18546, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 18595, "s": 18571, "text": "\nInternship Interviews\n" }, { "code": null, "e": 18622, "s": 18595, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 18640, "s": 18622, "text": "\nDesign Patterns\n" }, { "code": null, "e": 18665, "s": 18640, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18691, "s": 18665, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18830, "s": 18691, "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": 18834, "s": 18830, "text": "\nC\n" }, { "code": null, "e": 18840, "s": 18834, "text": "\nC++\n" }, { "code": null, "e": 18847, "s": 18840, "text": "\nJava\n" }, { "code": null, "e": 18856, "s": 18847, "text": "\nPython\n" }, { "code": null, "e": 18861, "s": 18856, "text": "\nC#\n" }, { "code": null, "e": 18874, "s": 18861, "text": "\nJavaScript\n" }, { "code": null, "e": 18883, "s": 18874, "text": "\njQuery\n" }, { "code": null, "e": 18889, "s": 18883, "text": "\nSQL\n" }, { "code": null, "e": 18895, "s": 18889, "text": "\nPHP\n" }, { "code": null, "e": 18903, "s": 18895, "text": "\nScala\n" }, { "code": null, "e": 18910, "s": 18903, "text": "\nPerl\n" }, { "code": null, "e": 18924, "s": 18910, "text": "\nGo Language\n" }, { "code": null, "e": 18931, "s": 18924, "text": "\nHTML\n" }, { "code": null, "e": 18937, "s": 18931, "text": "\nCSS\n" }, { "code": null, "e": 18946, "s": 18937, "text": "\nKotlin\n" }, { "code": null, "e": 19024, "s": 18946, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 19043, "s": 19024, "text": "\nMachine Learning\n" }, { "code": null, "e": 19058, "s": 19043, "text": "\nData Science\n" }, { "code": null, "e": 19271, "s": 19058, "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": 19285, "s": 19271, "text": "\nMathematics\n" }, { "code": null, "e": 19304, "s": 19285, "text": "\nOperating System\n" }, { "code": null, "e": 19311, "s": 19304, "text": "\nDBMS\n" }, { "code": null, "e": 19331, "s": 19311, "text": "\nComputer Networks\n" }, { "code": null, "e": 19372, "s": 19331, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 19396, "s": 19372, "text": "\nTheory of Computation\n" }, { "code": null, "e": 19414, "s": 19396, "text": "\nCompiler Design\n" }, { "code": null, "e": 19430, "s": 19414, "text": "\nDigital Logic\n" }, { "code": null, "e": 19453, "s": 19430, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 19670, "s": 19453, "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": 19700, "s": 19670, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19720, "s": 19700, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19744, "s": 19720, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19788, "s": 19744, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19806, "s": 19788, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19830, "s": 19806, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19861, "s": 19830, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19981, "s": 19861, "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": 19988, "s": 19981, "text": "\nHTML\n" }, { "code": null, "e": 19994, "s": 19988, "text": "\nCSS\n" }, { "code": null, "e": 20007, "s": 19994, "text": "\nJavaScript\n" }, { "code": null, "e": 20019, "s": 20007, "text": "\nAngularJS\n" }, { "code": null, "e": 20029, "s": 20019, "text": "\nReactJS\n" }, { "code": null, "e": 20038, "s": 20029, "text": "\nNodeJS\n" }, { "code": null, "e": 20050, "s": 20038, "text": "\nBootstrap\n" }, { "code": null, "e": 20059, "s": 20050, "text": "\njQuery\n" }, { "code": null, "e": 20065, "s": 20059, "text": "\nPHP\n" }, { "code": null, "e": 20160, "s": 20065, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 20187, "s": 20160, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 20212, "s": 20187, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 20276, "s": 20212, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 20297, "s": 20276, "text": "\nSchool Programming\n" }, { "code": null, "e": 20433, "s": 20297, "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": 20449, "s": 20433, "text": "\nNumber System\n" }, { "code": null, "e": 20459, "s": 20449, "text": "\nAlgebra\n" }, { "code": null, "e": 20474, "s": 20459, "text": "\nTrigonometry\n" }, { "code": null, "e": 20487, "s": 20474, "text": "\nStatistics\n" }, { "code": null, "e": 20501, "s": 20487, "text": "\nProbability\n" }, { "code": null, "e": 20512, "s": 20501, "text": "\nGeometry\n" }, { "code": null, "e": 20526, "s": 20512, "text": "\nMensuration\n" }, { "code": null, "e": 20537, "s": 20526, "text": "\nCalculus\n" }, { "code": null, "e": 20668, "s": 20537, "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": 20684, "s": 20668, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20700, "s": 20684, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20717, "s": 20700, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20734, "s": 20717, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20751, "s": 20734, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20918, "s": 20751, "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": 20943, "s": 20918, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20968, "s": 20943, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20994, "s": 20968, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21020, "s": 20994, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21046, "s": 21020, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21217, "s": 21046, "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": 21242, "s": 21217, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 21267, "s": 21242, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 21293, "s": 21267, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 21319, "s": 21293, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 21345, "s": 21319, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 21462, "s": 21345, "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": 21478, "s": 21462, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 21494, "s": 21478, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 21511, "s": 21494, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 21528, "s": 21511, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 21570, "s": 21528, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21715, "s": 21570, "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": 21759, "s": 21715, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21783, "s": 21759, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21830, "s": 21783, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21947, "s": 21830, "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": 21975, "s": 21947, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 22004, "s": 21975, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 22031, "s": 22004, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 22288, "s": 22031, "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\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n" }, { "code": null, "e": 22316, "s": 22288, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 22344, "s": 22316, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 22354, "s": 22344, "text": "\nProject\n" }, { "code": null, "e": 22374, "s": 22354, "text": "\nGeek of the Month\n" }, { "code": null, "e": 22401, "s": 22374, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 22420, "s": 22401, "text": "\nPlacement Course\n" }, { "code": null, "e": 22447, "s": 22420, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 22462, "s": 22447, "text": "\nTestimonials\n" }, { "code": null, "e": 22480, "s": 22462, "text": "\nStudent Chapter\n" }, { "code": null, "e": 22498, "s": 22480, "text": "\nGeek on the Top\n" }, { "code": null, "e": 22511, "s": 22498, "text": "\nInternship\n" }, { "code": null, "e": 22521, "s": 22511, "text": "\nCareers\n" }, { "code": null, "e": 22679, "s": 22521, "text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n" }, { "code": null, "e": 22703, "s": 22679, "text": "\nTop 50 Array Problems\n" }, { "code": null, "e": 22728, "s": 22703, "text": "\nTop 50 String Problems\n" }, { "code": null, "e": 22751, "s": 22728, "text": "\nTop 50 Tree Problems\n" }, { "code": null, "e": 22775, "s": 22751, "text": "\nTop 50 Graph Problems\n" }, { "code": null, "e": 22796, "s": 22775, "text": "\nTop 50 DP Problems\n" }, { "code": null, "e": 22834, "s": 22796, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 22907, "s": 22834, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 22924, "s": 22907, "text": "\nApply for Jobs\n" }, { "code": null, "e": 22937, "s": 22924, "text": "\nPost a Job\n" }, { "code": null, "e": 22950, "s": 22937, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 23136, "s": 22950, "text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n" }, { "code": null, "e": 23155, "s": 23136, "text": "\nAll DSA Problems\n" }, { "code": null, "e": 23176, "s": 23155, "text": "\nProblem of the Day\n" }, { "code": null, "e": 23212, "s": 23176, "text": "\nInterview Series: Weekly Contests\n" }, { "code": null, "e": 23248, "s": 23212, "text": "\nBi-Wizard Coding: School Contests\n" }, { "code": null, "e": 23270, "s": 23248, "text": "\nContests and Events\n" }, { "code": null, "e": 23291, "s": 23270, "text": "\nPractice SDE Sheet\n" }, { "code": null, "e": 23297, "s": 23291, "text": "GBlog" }, { "code": null, "e": 23305, "s": 23297, "text": "Puzzles" }, { "code": null, "e": 23318, "s": 23305, "text": "What's New ?" }, { "code": null, "e": 23324, "s": 23318, "text": "Array" }, { "code": null, "e": 23331, "s": 23324, "text": "Matrix" }, { "code": null, "e": 23339, "s": 23331, "text": "Strings" }, { "code": null, "e": 23347, "s": 23339, "text": "Hashing" }, { "code": null, "e": 23359, "s": 23347, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23359, "text": "Stack" }, { "code": null, "e": 23371, "s": 23365, "text": "Queue" }, { "code": null, "e": 23383, "s": 23371, "text": "Binary Tree" }, { "code": null, "e": 23402, "s": 23383, "text": "Binary Search Tree" }, { "code": null, "e": 23407, "s": 23402, "text": "Heap" }, { "code": null, "e": 23413, "s": 23407, "text": "Graph" }, { "code": null, "e": 23423, "s": 23413, "text": "Searching" }, { "code": null, "e": 23431, "s": 23423, "text": "Sorting" }, { "code": null, "e": 23448, "s": 23431, "text": "Divide & Conquer" }, { "code": null, "e": 23461, "s": 23448, "text": "Mathematical" }, { "code": null, "e": 23471, "s": 23461, "text": "Geometric" }, { "code": null, "e": 23479, "s": 23471, "text": "Bitwise" }, { "code": null, "e": 23486, "s": 23479, "text": "Greedy" }, { "code": null, "e": 23499, "s": 23486, "text": "Backtracking" }, { "code": null, "e": 23516, "s": 23499, "text": "Branch and Bound" }, { "code": null, "e": 23536, "s": 23516, "text": "Dynamic Programming" }, { "code": null, "e": 23554, "s": 23536, "text": "Pattern Searching" }, { "code": null, "e": 23565, "s": 23554, "text": "Randomized" }, { "code": null, "e": 23605, "s": 23565, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 23643, "s": 23605, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 23694, "s": 23643, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 23724, "s": 23694, "text": "Graph and its representations" }, { "code": null, "e": 23775, "s": 23724, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 23833, "s": 23775, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 23853, "s": 23833, "text": "Topological Sorting" }, { "code": null, "e": 23886, "s": 23853, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 23917, "s": 23886, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 23950, "s": 23917, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 24025, "s": 23950, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 24093, "s": 24025, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 24129, "s": 24093, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 24159, "s": 24129, "text": "Strongly Connected Components" }, { "code": null, "e": 24206, "s": 24159, "text": "Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 24256, "s": 24206, "text": "Minimum number of swaps required to sort an array" }, { "code": null, "e": 24327, "s": 24256, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 24377, "s": 24327, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 24425, "s": 24377, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 24462, "s": 24425, "text": "Shortest path in an unweighted graph" }, { "code": null, "e": 24503, "s": 24462, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 24551, "s": 24503, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 24595, "s": 24551, "text": "Connected Components in an undirected graph" }, { "code": null, "e": 24661, "s": 24595, "text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)" }, { "code": null, "e": 24714, "s": 24661, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 24749, "s": 24714, "text": "Applications of Depth First Search" }, { "code": null, "e": 24785, "s": 24749, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 24848, "s": 24785, "text": "Dijkstra's Shortest Path Algorithm using priority_queue of STL" }, { "code": null, "e": 24883, "s": 24848, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 24924, "s": 24883, "text": "Kahn's algorithm for Topological Sorting" }, { "code": null, "e": 24964, "s": 24924, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 25002, "s": 24964, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 25053, "s": 25002, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 25083, "s": 25053, "text": "Graph and its representations" }, { "code": null, "e": 25134, "s": 25083, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 25192, "s": 25134, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 25212, "s": 25192, "text": "Topological Sorting" }, { "code": null, "e": 25245, "s": 25212, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 25276, "s": 25245, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 25309, "s": 25276, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 25384, "s": 25309, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 25452, "s": 25384, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 25488, "s": 25452, "text": "Detect cycle in an undirected graph" }, { "code": null, "e": 25518, "s": 25488, "text": "Strongly Connected Components" }, { "code": null, "e": 25565, "s": 25518, "text": "Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 25615, "s": 25565, "text": "Minimum number of swaps required to sort an array" }, { "code": null, "e": 25686, "s": 25615, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 25736, "s": 25686, "text": "Ford-Fulkerson Algorithm for Maximum Flow Problem" }, { "code": null, "e": 25784, "s": 25736, "text": "Check whether a given graph is Bipartite or not" }, { "code": null, "e": 25821, "s": 25784, "text": "Shortest path in an unweighted graph" }, { "code": null, "e": 25862, "s": 25821, "text": "Iterative Depth First Traversal of Graph" }, { "code": null, "e": 25910, "s": 25862, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 25954, "s": 25910, "text": "Connected Components in an undirected graph" }, { "code": null, "e": 26020, "s": 25954, "text": "Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)" }, { "code": null, "e": 26073, "s": 26020, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 26108, "s": 26073, "text": "Applications of Depth First Search" }, { "code": null, "e": 26144, "s": 26108, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 26207, "s": 26144, "text": "Dijkstra's Shortest Path Algorithm using priority_queue of STL" }, { "code": null, "e": 26242, "s": 26207, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 26283, "s": 26242, "text": "Kahn's algorithm for Topological Sorting" }, { "code": null, "e": 26309, "s": 26283, "text": "Difficulty Level :\nMedium" }, { "code": null, "e": 26604, "s": 26309, "text": "Given a set of ‘n’ vertices and ‘m’ edges of an undirected simple graph (no parallel edges and no self-loop), find the number of single-cycle-components present in the graph. A single-cyclic-component is a graph of n nodes containing a single cycle through all nodes of the component.Example: " }, { "code": null, "e": 26658, "s": 26604, "text": "Let us consider the following graph with 15 vertices." }, { "code": null, "e": 27118, "s": 26658, "text": "Input: V = 15, E = 14\n 1 10 // edge 1\n 1 5 // edge 2\n 5 10 // edge 3\n 2 9 // ..\n 9 15 // ..\n 2 15 // ..\n 2 12 // ..\n 12 15 // ..\n 13 8 // ..\n 6 14 // ..\n 14 3 // ..\n 3 7 // ..\n 7 11 // edge 13\n 11 6 // edge 14\nOutput :2\nIn the above-mentioned example, the two \nsingle-cyclic-components are composed of \nvertices (1, 10, 5) and (6, 11, 7, 3, 14) \nrespectively." }, { "code": null, "e": 28034, "s": 27118, "text": "Now we can easily see that a single-cycle-component is a connected component where every vertex has the degree as two. Therefore, in order to solve this problem we first identify all the connected components of the disconnected graph. For this, we use depth-first search algorithm. For the DFS algorithm to work, it is required to maintain an array ‘found’ to keep an account of all the vertices that have been discovered by the recursive function DFS. Once all the elements of a particular connected component are discovered (like vertices(9, 2, 15, 12) form a connected graph component ), we check if all the vertices in the component are having the degree equal to two. If yes, we increase the counter variable ‘count’ which denotes the number of single-cycle-components found in the given graph. To keep an account of the component we are presently dealing with, we may use a vector array ‘curr_graph’ as well. " }, { "code": null, "e": 28038, "s": 28034, "text": "C++" }, { "code": null, "e": 28043, "s": 28038, "text": "Java" }, { "code": null, "e": 28051, "s": 28043, "text": "Python3" }, { "code": null, "e": 28054, "s": 28051, "text": "C#" }, { "code": null, "e": 28065, "s": 28054, "text": "Javascript" }, { "code": "// CPP program to find single cycle components// in a graph.#include <bits/stdc++.h>using namespace std; const int N = 100000; // degree of all the verticesint degree[N]; // to keep track of all the vertices covered// till nowbool found[N]; // all the vertices in a particular// connected component of the graphvector<int> curr_graph; // adjacency listvector<int> adj_list[N]; // depth-first traversal to identify all the// nodes in a particular connected graph// componentvoid DFS(int v){ found[v] = true; curr_graph.push_back(v); for (int it : adj_list[v]) if (!found[it]) DFS(it);} // function to add an edge in the graphvoid addEdge(vector<int> adj_list[N], int src, int dest){ // for index decrement both src and dest. src--, dest--; adj_list[src].push_back(dest); adj_list[dest].push_back(src); degree[src]++; degree[dest]++;} int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v : curr_graph) { if (degree[v] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} int main(){ // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge(adj_list, 1, 10); addEdge(adj_list, 1, 5); addEdge(adj_list, 5, 10); addEdge(adj_list, 2, 9); addEdge(adj_list, 9, 15); addEdge(adj_list, 2, 15); addEdge(adj_list, 2, 12); addEdge(adj_list, 12, 15); addEdge(adj_list, 13, 8); addEdge(adj_list, 6, 14); addEdge(adj_list, 14, 3); addEdge(adj_list, 3, 7); addEdge(adj_list, 7, 11); addEdge(adj_list, 11, 6); cout << countSingleCycles(n, m); return 0;}", "e": 30112, "s": 28065, "text": null }, { "code": "// Java program to find single cycle components// in a graph.import java.util.*; class GFG{ static int N = 100000; // degree of all the verticesstatic int degree[] = new int[N]; // to keep track of all the vertices covered// till nowstatic boolean found[] = new boolean[N]; // all the vertices in a particular// connected component of the graphstatic Vector<Integer> curr_graph = new Vector<Integer>(); // adjacency liststatic Vector<Vector<Integer>> adj_list = new Vector<Vector<Integer>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){ found[v] = true; curr_graph.add(v); for (int it = 0 ;it < adj_list.get(v).size(); it++) if (!found[adj_list.get(v).get(it)]) DFS(adj_list.get(v).get(it));} // function to add an edge in the graphstatic void addEdge( int src,int dest){ // for index decrement both src and dest. src--; dest--; adj_list.get(src).add(dest); adj_list.get(dest).add(src); degree[src]++; degree[dest]++;} static int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v = 0 ; v < curr_graph.size(); v++) { if (degree[curr_graph.get(v)] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codepublic static void main(String args[]){ for(int i = 0; i < N + 1; i++) adj_list.add(new Vector<Integer>()); // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge( 1, 10); addEdge( 1, 5); addEdge( 5, 10); addEdge( 2, 9); addEdge( 9, 15); addEdge( 2, 15); addEdge( 2, 12); addEdge( 12, 15); addEdge( 13, 8); addEdge( 6, 14); addEdge( 14, 3); addEdge( 3, 7); addEdge( 7, 11); addEdge( 11, 6); System.out.println(countSingleCycles(n, m));}} // This code is contributed by Arnab Kundu", "e": 32460, "s": 30112, "text": null }, { "code": "# Python3 program to find single# cycle components in a graph.N = 100000 # degree of all the verticesdegree = [0] * N # to keep track of all the# vertices covered till nowfound = [None] * N # All the vertices in a particular# connected component of the graphcurr_graph = [] # adjacency listadj_list = [[] for i in range(N)] # depth-first traversal to identify# all the nodes in a particular# connected graph componentdef DFS(v): found[v] = True curr_graph.append(v) for it in adj_list[v]: if not found[it]: DFS(it) # function to add an edge in the graphdef addEdge(adj_list, src, dest): # for index decrement both src and dest. src, dest = src - 1, dest - 1 adj_list[src].append(dest) adj_list[dest].append(src) degree[src] += 1 degree[dest] += 1 def countSingleCycles(n, m): # count of cycle graph components count = 0 for i in range(0, n): if not found[i]: curr_graph.clear() DFS(i) # traversing the nodes of the # current graph component flag = 1 for v in curr_graph: if degree[v] == 2: continue else: flag = 0 break if flag == 1: count += 1 return count # Driver Codeif __name__ == \"__main__\": # n->number of vertices # m->number of edges n, m = 15, 14 addEdge(adj_list, 1, 10) addEdge(adj_list, 1, 5) addEdge(adj_list, 5, 10) addEdge(adj_list, 2, 9) addEdge(adj_list, 9, 15) addEdge(adj_list, 2, 15) addEdge(adj_list, 2, 12) addEdge(adj_list, 12, 15) addEdge(adj_list, 13, 8) addEdge(adj_list, 6, 14) addEdge(adj_list, 14, 3) addEdge(adj_list, 3, 7) addEdge(adj_list, 7, 11) addEdge(adj_list, 11, 6) print(countSingleCycles(n, m)) # This code is contributed by Rituraj Jain", "e": 34369, "s": 32460, "text": null }, { "code": "// C# program to find single cycle components// in a graph.using System;using System.Collections.Generic; class GFG{static int N = 100000; // degree of all the verticesstatic int []degree = new int[N]; // to keep track of all the vertices covered// till nowstatic bool []found = new bool[N]; // all the vertices in a particular// connected component of the graphstatic List<int> curr_graph = new List<int>(); // adjacency liststatic List<List<int>> adj_list = new List<List<int>>(); // depth-first traversal to identify all the// nodes in a particular connected graph// componentstatic void DFS(int v){ found[v] = true; curr_graph.Add(v); for (int it = 0; it < adj_list[v].Count; it++) if (!found[adj_list[v][it]]) DFS(adj_list[v][it]);} // function to add an edge in the graphstatic void addEdge(int src,int dest){ // for index decrement both src and dest. src--; dest--; adj_list[src].Add(dest); adj_list[dest].Add(src); degree[src]++; degree[dest]++;} static int countSingleCycles(int n, int m){ // count of cycle graph components int count = 0; for (int i = 0; i < n; ++i) { if (!found[i]) { curr_graph.Clear(); DFS(i); // traversing the nodes of the // current graph component int flag = 1; for (int v = 0 ; v < curr_graph.Count; v++) { if (degree[curr_graph[v]] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codepublic static void Main(String []args){ for(int i = 0; i < N + 1; i++) adj_list.Add(new List<int>()); // n->number of vertices // m->number of edges int n = 15, m = 14; addEdge(1, 10); addEdge(1, 5); addEdge(5, 10); addEdge(2, 9); addEdge(9, 15); addEdge(2, 15); addEdge(2, 12); addEdge(12, 15); addEdge(13, 8); addEdge(6, 14); addEdge(14, 3); addEdge(3, 7); addEdge(7, 11); addEdge(11, 6); Console.WriteLine(countSingleCycles(n, m));}} // This code is contributed by PrinciRaj1992", "e": 36650, "s": 34369, "text": null }, { "code": "<script> // JavaScript program to find single cycle components// in a graph. let N = 100000; // degree of all the verticeslet degree=new Array(N);for(let i=0;i<N;i++) degree[i]=0;// to keep track of all the vertices covered// till nowlet found=new Array(N);for(let i=0;i<N;i++) found[i]=0; // all the vertices in a particular// connected component of the graphlet curr_graph = []; // adjacency listlet adj_list = []; // depth-first traversal to identify all the// nodes in a particular connected graph// componentfunction DFS(v){ found[v] = true; curr_graph.push(v); for (let it = 0 ;it < adj_list[v].length; it++) if (!found[adj_list[v][it]]) DFS(adj_list[v][it]);} // function to add an edge in the graphfunction addEdge(src,dest){ // for index decrement both src and dest. src--; dest--; adj_list[src].push(dest); adj_list[dest].push(src); degree[src]++; degree[dest]++;} function countSingleCycles(n,m){ // count of cycle graph components let count = 0; for (let i = 0; i < n; ++i) { if (!found[i]) { curr_graph=[]; DFS(i); // traversing the nodes of the // current graph component let flag = 1; for (let v = 0 ; v < curr_graph.length; v++) { if (degree[curr_graph[v]] == 2) continue; else { flag = 0; break; } } if (flag == 1) { count++; } } } return(count);} // Driver codefor(let i = 0; i < N + 1; i++) adj_list.push([]); // n->number of vertices// m->number of edgeslet n = 15, m = 14;addEdge( 1, 10);addEdge( 1, 5);addEdge( 5, 10);addEdge( 2, 9);addEdge( 9, 15);addEdge( 2, 15);addEdge( 2, 12);addEdge( 12, 15);addEdge( 13, 8);addEdge( 6, 14);addEdge( 14, 3);addEdge( 3, 7);addEdge( 7, 11);addEdge( 11, 6); document.write(countSingleCycles(n, m)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 38737, "s": 36650, "text": null }, { "code": null, "e": 38739, "s": 38737, "text": "2" }, { "code": null, "e": 38797, "s": 38741, "text": "Hence, total number of cycle graph component is found. " }, { "code": null, "e": 38809, "s": 38797, "text": "PiyushKumar" }, { "code": null, "e": 38822, "s": 38809, "text": "rituraj_jain" }, { "code": null, "e": 38833, "s": 38822, "text": "andrew1234" }, { "code": null, "e": 38847, "s": 38833, "text": "princiraj1992" }, { "code": null, "e": 38868, "s": 38847, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38872, "s": 38868, "text": "DFS" }, { "code": null, "e": 38891, "s": 38872, "text": "graph-connectivity" }, { "code": null, "e": 38903, "s": 38891, "text": "graph-cycle" }, { "code": null, "e": 38909, "s": 38903, "text": "Graph" }, { "code": null, "e": 38916, "s": 38909, "text": "Greedy" }, { "code": null, "e": 38923, "s": 38916, "text": "Greedy" }, { "code": null, "e": 38927, "s": 38923, "text": "DFS" }, { "code": null, "e": 38933, "s": 38927, "text": "Graph" }, { "code": null, "e": 39031, "s": 38933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39072, "s": 39031, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 39108, "s": 39072, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 39150, "s": 39108, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 39177, "s": 39150, "text": "Maximum Bipartite Matching" }, { "code": null, "e": 39232, "s": 39177, "text": "Graph Coloring | Set 1 (Introduction and Applications)" }, { "code": null, "e": 39259, "s": 39232, "text": "Program for array rotation" }, { "code": null, "e": 39319, "s": 39259, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39350, "s": 39319, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 39369, "s": 39350, "text": "Coin Change | DP-7" } ]
Class getDeclaredMethods() method in Java with Examples - GeeksforGeeks
25 Jan, 2022 The getDeclaredMethods() method of java.lang.Class class is used to get the methods of this class, which are the methods that are private, public, protected or default and its members or the members of its member classes and interfaces, but not the inherited methods. The method returns the methods of this class in the form of an array of Method objects. Syntax: public Method[] getDeclaredMethods() throws SecurityException Parameter: This method does not accept any parameter.Return Value: This method returns the methods of this class in the form of an array of Method objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredMethods() method.Example 1: Java // Java program to demonstrate getDeclaredMethods() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the methods of myClass // using getDeclaredMethods() method System.out.println( "DeclaredMethods of myClass: " + Arrays.toString( myClass.getDeclaredMethods())); }} Class represented by myClass: class Test DeclaredMethods of myClass: [public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException] Example 2: Java // Java program to demonstrate getDeclaredMethods() method import java.util.*; class Main { public Object obj; private void function() {} Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the methods of myClass // using getDeclaredMethods() method System.out.println( "DeclaredMethods of myClass: " + Arrays.toString( myClass.getDeclaredMethods())); }} Class represented by myClass: class Main DeclaredMethods of myClass: [public static void Main.main(java.lang.String[]) throws java.lang.ClassNotFoundException, private void Main.function()] Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethods– adnanirshad158 Java-Functions Java-lang package Java.lang.Class Java 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 Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n25 Jan, 2022" }, { "code": null, "e": 25591, "s": 25225, "text": "The getDeclaredMethods() method of java.lang.Class class is used to get the methods of this class, which are the methods that are private, public, protected or default and its members or the members of its member classes and interfaces, but not the inherited methods. The method returns the methods of this class in the form of an array of Method objects. Syntax: " }, { "code": null, "e": 25668, "s": 25591, "text": "public Method[] getDeclaredMethods()\n throws SecurityException" }, { "code": null, "e": 26015, "s": 25668, "text": "Parameter: This method does not accept any parameter.Return Value: This method returns the methods of this class in the form of an array of Method objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getDeclaredMethods() method.Example 1: " }, { "code": null, "e": 26020, "s": 26015, "text": "Java" }, { "code": "// Java program to demonstrate getDeclaredMethods() method import java.util.*; public class Test { public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the methods of myClass // using getDeclaredMethods() method System.out.println( \"DeclaredMethods of myClass: \" + Arrays.toString( myClass.getDeclaredMethods())); }}", "e": 26645, "s": 26020, "text": null }, { "code": null, "e": 26806, "s": 26645, "text": "Class represented by myClass: class Test DeclaredMethods of myClass: [public static void Test.main(java.lang.String[]) throws java.lang.ClassNotFoundException] " }, { "code": null, "e": 26820, "s": 26808, "text": "Example 2: " }, { "code": null, "e": 26825, "s": 26820, "text": "Java" }, { "code": "// Java program to demonstrate getDeclaredMethods() method import java.util.*; class Main { public Object obj; private void function() {} Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the methods of myClass // using getDeclaredMethods() method System.out.println( \"DeclaredMethods of myClass: \" + Arrays.toString( myClass.getDeclaredMethods())); }}", "e": 27573, "s": 26825, "text": null }, { "code": null, "e": 27764, "s": 27573, "text": "Class represented by myClass: class Main DeclaredMethods of myClass: [public static void Main.main(java.lang.String[]) throws java.lang.ClassNotFoundException, private void Main.function()] " }, { "code": null, "e": 27861, "s": 27766, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredMethods– " }, { "code": null, "e": 27876, "s": 27861, "text": "adnanirshad158" }, { "code": null, "e": 27891, "s": 27876, "text": "Java-Functions" }, { "code": null, "e": 27909, "s": 27891, "text": "Java-lang package" }, { "code": null, "e": 27925, "s": 27909, "text": "Java.lang.Class" }, { "code": null, "e": 27930, "s": 27925, "text": "Java" }, { "code": null, "e": 27935, "s": 27930, "text": "Java" }, { "code": null, "e": 28033, "s": 27935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28048, "s": 28033, "text": "Stream In Java" }, { "code": null, "e": 28069, "s": 28048, "text": "Constructors in Java" }, { "code": null, "e": 28088, "s": 28069, "text": "Exceptions in Java" }, { "code": null, "e": 28118, "s": 28088, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28164, "s": 28118, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28181, "s": 28164, "text": "Generics in Java" }, { "code": null, "e": 28202, "s": 28181, "text": "Introduction to Java" }, { "code": null, "e": 28245, "s": 28202, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28281, "s": 28245, "text": "Internal Working of HashMap in Java" } ]
Cartesian Tree Sorting - GeeksforGeeks
19 May, 2016 Prerequisites : Cartesian Tree Cartesian Sort is an Adaptive Sorting as it sorts the data faster if data is partially sorted. In fact, there are very few sorting algorithms that make use of this fact. For example consider the array {5, 10, 40, 30, 28}. The input data is partially sorted too as only one swap between “40” and “28” results in a completely sorted order. See how Cartesian Tree Sort will take advantage of this fact below. Below are steps used for sorting. Step 1 : Build a (min-heap) Cartesian Tree from the given input sequence. Step 2 : Starting from the root of the built Cartesian Tree, we push the nodes in a priority queue.Then we pop the node at the top of the priority queue and push the children of the popped node in the priority queue in a pre-order manner. Pop the node at the top of the priority queue and add it to a list.Push left child of the popped node first (if present).Push right child of the popped node next (if present). Pop the node at the top of the priority queue and add it to a list. Push left child of the popped node first (if present). Push right child of the popped node next (if present). How to build (min-heap) Cartesian Tree?Building min-heap is similar to building a (max-heap) Cartesian Tree (discussed in previous post), except the fact that now we scan upward from the node’s parent up to the root of the tree until a node is found whose value is smaller (and not larger as in the case of a max-heap Cartesian Tree) than the current one and then accordingly reconfigure links to build the min-heap Cartesian tree. Why not to use only priority queue?One might wonder that using priority queue would anyway result in a sorted data if we simply insert the numbers of the input array one by one in the priority queue (i.e- without constructing the Cartesian tree). But the time taken differs a lot. Suppose we take the input array – {5, 10, 40, 30, 28} If we simply insert the input array numbers one by one (without using a Cartesian tree), then we may have to waste a lot of operations in adjusting the queue order everytime we insert the numbers (just like a typical heap performs those operations when a new number is inserted, as priority queue is nothing but a heap). Whereas, here we can see that using a Cartesian tree took only 5 operations (see the above two figures in which we are continuously pushing and popping the nodes of Cartesian tree), which is linear as there are 5 numbers in the input array also. So we see that the best case of Cartesian Tree sort is O(n), a thing where heap-sort will take much more number of operations, because it doesn’t make advantage of the fact that the input data is partially sorted. Why pre-order traversal?The answer to this is that since Cartesian Tree is basically a heap- data structure and hence follows all the properties of a heap. Thus the root node is always smaller than both of its children. Hence, we use a pre-order fashion popping-and-pushing as in this, the root node is always pushed earlier than its children inside the priority queue and since the root node is always less than both its child, so we don’t have to do extra operations inside the priority queue. Refer to the below figure for better understanding- // A C++ program to implement Cartesian Tree sort// Note that in this program we will build a min-heap// Cartesian Tree and not max-heap.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left, *right;}; // Creating a shortcut for int, Node* pair typetypedef pair<int, Node*> iNPair; // This function sorts by pushing and popping the// Cartesian Tree nodes in a pre-order like fashionvoid pQBasedTraversal(Node* root){ // We will use a priority queue to sort the // partially-sorted data efficiently. // Unlike Heap, Cartesian tree makes use of // the fact that the data is partially sorted priority_queue <iNPair, vector<iNPair>, greater<iNPair>> pQueue; pQueue.push (make_pair (root->data,root)); // Resembles a pre-order traverse as first data // is printed then the left and then right child. while (! pQueue.empty()) { iNPair popped_pair = pQueue.top(); printf("%d ",popped_pair.first); pQueue.pop(); if (popped_pair.second->left != NULL) pQueue.push (make_pair(popped_pair.second->left->data, popped_pair.second->left)); if (popped_pair.second->right != NULL) pQueue.push (make_pair(popped_pair.second->right->data, popped_pair.second->right)); } return;} Node *buildCartesianTreeUtil(int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return NULL; Node *temp = new Node; temp->data = arr[root]; temp->left = buildCartesianTreeUtil(leftchild[root], arr, parent, leftchild, rightchild); temp->right = buildCartesianTreeUtil(rightchild[root], arr, parent, leftchild, rightchild); return temp ;} // A function to create the Cartesian Tree in O(N) timeNode *buildCartesianTree(int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int parent[n],leftchild[n],rightchild[n]; // Initialize all array values as -1 memset(parent, -1, sizeof(parent)); memset(leftchild, -1, sizeof(leftchild)); memset(rightchild, -1, sizeof(rightchild)); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i=1; i<=n-1; i++) { last = i-1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is smaller than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] >= arr[i] && last != root) last = parent[last]; // arr[i] is the smallest element yet; make it // new root if (arr[last] >= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last]= i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} // Sorts an input arrayint printSortedArr(int arr[], int n){ // Build a cartesian tree Node *root = buildCartesianTree(arr, n); printf("The sorted array is-\n"); // Do pr-order traversal and insert // in priority queue pQBasedTraversal(root);} /* Driver program to test above functions */int main(){ /* Given input array- {5,10,40,30,28}, it's corresponding unique Cartesian Tree is- 5 \ 10 \ 28 / 30 / 40 */ int arr[] = {5, 10, 40, 30, 28}; int n = sizeof(arr)/sizeof(arr[0]); printSortedArr(arr, n); return(0);} Output : The sorted array is- 5 10 28 30 40 Time Complexity : O(n) best-case behaviour (when the input data is partially sorted), O(n log n) worst-case behavior (when the input data is not partially sorted) Auxiliary Space : We use a priority queue and a Cartesian tree data structure. Now, at any moment of time the size of the priority queue doesn’t exceeds the size of the input array, as we are constantly pushing and popping the nodes. Hence we are using O(n) auxiliary space. References :https://en.wikipedia.org/wiki/Adaptive_sorthttp://11011110.livejournal.com/283412.htmlhttp://gradbot.blogspot.in/2010/06/cartesian-tree-sort.htmlhttp://www.keithschwarz.com/interesting/code/?dir=cartesian-tree-sorthttps://en.wikipedia.org/wiki/Cartesian_tree#Application_in_sorting This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 Advanced Data Structure Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Introduction with example Ordered Set and GNU C++ PBDS Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Binary Indexed Tree or Fenwick Tree
[ { "code": null, "e": 25647, "s": 25619, "text": "\n19 May, 2016" }, { "code": null, "e": 25678, "s": 25647, "text": "Prerequisites : Cartesian Tree" }, { "code": null, "e": 25848, "s": 25678, "text": "Cartesian Sort is an Adaptive Sorting as it sorts the data faster if data is partially sorted. In fact, there are very few sorting algorithms that make use of this fact." }, { "code": null, "e": 26084, "s": 25848, "text": "For example consider the array {5, 10, 40, 30, 28}. The input data is partially sorted too as only one swap between “40” and “28” results in a completely sorted order. See how Cartesian Tree Sort will take advantage of this fact below." }, { "code": null, "e": 26118, "s": 26084, "text": "Below are steps used for sorting." }, { "code": null, "e": 26192, "s": 26118, "text": "Step 1 : Build a (min-heap) Cartesian Tree from the given input sequence." }, { "code": null, "e": 26431, "s": 26192, "text": "Step 2 : Starting from the root of the built Cartesian Tree, we push the nodes in a priority queue.Then we pop the node at the top of the priority queue and push the children of the popped node in the priority queue in a pre-order manner." }, { "code": null, "e": 26607, "s": 26431, "text": "Pop the node at the top of the priority queue and add it to a list.Push left child of the popped node first (if present).Push right child of the popped node next (if present)." }, { "code": null, "e": 26675, "s": 26607, "text": "Pop the node at the top of the priority queue and add it to a list." }, { "code": null, "e": 26730, "s": 26675, "text": "Push left child of the popped node first (if present)." }, { "code": null, "e": 26785, "s": 26730, "text": "Push right child of the popped node next (if present)." }, { "code": null, "e": 27217, "s": 26785, "text": "How to build (min-heap) Cartesian Tree?Building min-heap is similar to building a (max-heap) Cartesian Tree (discussed in previous post), except the fact that now we scan upward from the node’s parent up to the root of the tree until a node is found whose value is smaller (and not larger as in the case of a max-heap Cartesian Tree) than the current one and then accordingly reconfigure links to build the min-heap Cartesian tree." }, { "code": null, "e": 27464, "s": 27217, "text": "Why not to use only priority queue?One might wonder that using priority queue would anyway result in a sorted data if we simply insert the numbers of the input array one by one in the priority queue (i.e- without constructing the Cartesian tree)." }, { "code": null, "e": 27498, "s": 27464, "text": "But the time taken differs a lot." }, { "code": null, "e": 27552, "s": 27498, "text": "Suppose we take the input array – {5, 10, 40, 30, 28}" }, { "code": null, "e": 27873, "s": 27552, "text": "If we simply insert the input array numbers one by one (without using a Cartesian tree), then we may have to waste a lot of operations in adjusting the queue order everytime we insert the numbers (just like a typical heap performs those operations when a new number is inserted, as priority queue is nothing but a heap)." }, { "code": null, "e": 28333, "s": 27873, "text": "Whereas, here we can see that using a Cartesian tree took only 5 operations (see the above two figures in which we are continuously pushing and popping the nodes of Cartesian tree), which is linear as there are 5 numbers in the input array also. So we see that the best case of Cartesian Tree sort is O(n), a thing where heap-sort will take much more number of operations, because it doesn’t make advantage of the fact that the input data is partially sorted." }, { "code": null, "e": 28829, "s": 28333, "text": "Why pre-order traversal?The answer to this is that since Cartesian Tree is basically a heap- data structure and hence follows all the properties of a heap. Thus the root node is always smaller than both of its children. Hence, we use a pre-order fashion popping-and-pushing as in this, the root node is always pushed earlier than its children inside the priority queue and since the root node is always less than both its child, so we don’t have to do extra operations inside the priority queue." }, { "code": null, "e": 28881, "s": 28829, "text": "Refer to the below figure for better understanding-" }, { "code": "// A C++ program to implement Cartesian Tree sort// Note that in this program we will build a min-heap// Cartesian Tree and not max-heap.#include<bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node{ int data; Node *left, *right;}; // Creating a shortcut for int, Node* pair typetypedef pair<int, Node*> iNPair; // This function sorts by pushing and popping the// Cartesian Tree nodes in a pre-order like fashionvoid pQBasedTraversal(Node* root){ // We will use a priority queue to sort the // partially-sorted data efficiently. // Unlike Heap, Cartesian tree makes use of // the fact that the data is partially sorted priority_queue <iNPair, vector<iNPair>, greater<iNPair>> pQueue; pQueue.push (make_pair (root->data,root)); // Resembles a pre-order traverse as first data // is printed then the left and then right child. while (! pQueue.empty()) { iNPair popped_pair = pQueue.top(); printf(\"%d \",popped_pair.first); pQueue.pop(); if (popped_pair.second->left != NULL) pQueue.push (make_pair(popped_pair.second->left->data, popped_pair.second->left)); if (popped_pair.second->right != NULL) pQueue.push (make_pair(popped_pair.second->right->data, popped_pair.second->right)); } return;} Node *buildCartesianTreeUtil(int root, int arr[], int parent[], int leftchild[], int rightchild[]){ if (root == -1) return NULL; Node *temp = new Node; temp->data = arr[root]; temp->left = buildCartesianTreeUtil(leftchild[root], arr, parent, leftchild, rightchild); temp->right = buildCartesianTreeUtil(rightchild[root], arr, parent, leftchild, rightchild); return temp ;} // A function to create the Cartesian Tree in O(N) timeNode *buildCartesianTree(int arr[], int n){ // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int parent[n],leftchild[n],rightchild[n]; // Initialize all array values as -1 memset(parent, -1, sizeof(parent)); memset(leftchild, -1, sizeof(leftchild)); memset(rightchild, -1, sizeof(rightchild)); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i=1; i<=n-1; i++) { last = i-1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is smaller than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] >= arr[i] && last != root) last = parent[last]; // arr[i] is the smallest element yet; make it // new root if (arr[last] >= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last]= i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild));} // Sorts an input arrayint printSortedArr(int arr[], int n){ // Build a cartesian tree Node *root = buildCartesianTree(arr, n); printf(\"The sorted array is-\\n\"); // Do pr-order traversal and insert // in priority queue pQBasedTraversal(root);} /* Driver program to test above functions */int main(){ /* Given input array- {5,10,40,30,28}, it's corresponding unique Cartesian Tree is- 5 \\ 10 \\ 28 / 30 / 40 */ int arr[] = {5, 10, 40, 30, 28}; int n = sizeof(arr)/sizeof(arr[0]); printSortedArr(arr, n); return(0);}", "e": 33509, "s": 28881, "text": null }, { "code": null, "e": 33518, "s": 33509, "text": "Output :" }, { "code": null, "e": 33553, "s": 33518, "text": "The sorted array is-\n5 10 28 30 40" }, { "code": null, "e": 33716, "s": 33553, "text": "Time Complexity : O(n) best-case behaviour (when the input data is partially sorted), O(n log n) worst-case behavior (when the input data is not partially sorted)" }, { "code": null, "e": 33991, "s": 33716, "text": "Auxiliary Space : We use a priority queue and a Cartesian tree data structure. Now, at any moment of time the size of the priority queue doesn’t exceeds the size of the input array, as we are constantly pushing and popping the nodes. Hence we are using O(n) auxiliary space." }, { "code": null, "e": 34285, "s": 33991, "text": "References :https://en.wikipedia.org/wiki/Adaptive_sorthttp://11011110.livejournal.com/283412.htmlhttp://gradbot.blogspot.in/2010/06/cartesian-tree-sort.htmlhttp://www.keithschwarz.com/interesting/code/?dir=cartesian-tree-sorthttps://en.wikipedia.org/wiki/Cartesian_tree#Application_in_sorting" }, { "code": null, "e": 34555, "s": 34285, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 34679, "s": 34555, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 34703, "s": 34679, "text": "Advanced Data Structure" }, { "code": null, "e": 34711, "s": 34703, "text": "Sorting" }, { "code": null, "e": 34719, "s": 34711, "text": "Sorting" }, { "code": null, "e": 34817, "s": 34719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34857, "s": 34817, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 34886, "s": 34857, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 34918, "s": 34886, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 34947, "s": 34918, "text": "Disjoint Set Data Structures" } ]
Maximum product subset of an array - GeeksforGeeks
18 Jun, 2021 Given an array a, we have to find maximum product possible with the subset of elements present in the array. The maximum product can be single element also.Examples: Input: a[] = { -1, -1, -2, 4, 3 } Output: 24 Explanation : Maximum product will be ( -2 * -1 * 4 * 3 ) = 24 Input: a[] = { -1, 0 } Output: 0 Explanation: 0(single element) is maximum product possible Input: a[] = { 0, 0, 0 } Output: 0 A simple solution is to generate all subsets, find product of every subset and return maximum product.A better solution is to use the below facts. If there are even number of negative numbers and no zeros, result is simply product of allIf there are odd number of negative numbers and no zeros, result is product of all except the negative integer with the least absolute value.If there are zeros, result is product of all except these zeros with one exceptional case. The exceptional case is when there is one negative number and all other elements are 0. In this case, result is 0. If there are even number of negative numbers and no zeros, result is simply product of all If there are odd number of negative numbers and no zeros, result is product of all except the negative integer with the least absolute value. If there are zeros, result is product of all except these zeros with one exceptional case. The exceptional case is when there is one negative number and all other elements are 0. In this case, result is 0. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to find maximum product of// a subset.#include <bits/stdc++.h>using namespace std; int maxProductSubset(int a[], int n){ if (n == 1) return a[0]; // Find count of negative numbers, count // of zeros, negative number // with least absolute value // and product of non-zero numbers int max_neg = INT_MIN; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value if (a[i] < 0) { count_neg++; max_neg = max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) return 0; // If there are odd number of // negative numbers if (count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) return 0; // Otherwise result is product of // all non-zeros divided by //negative number with // least absolute value prod = prod / max_neg; } return prod;} // Driver Codeint main(){ int a[] = { -1, -1, -2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << maxProductSubset(a, n); return 0;} // Java program to find maximum product of// a subset. class GFG { static int maxProductSubset(int a[], int n) { if (n == 1) { return a[0]; } // Find count of negative numbers, count // of zeros, negative number // with least absolute value // and product of non-zero numbers int max_neg = Integer.MIN_VALUE; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) { return 0; } // If there are odd number of // negative numbers if (count_neg % 2 == 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) { return 0; } // Otherwise result is product of // all non-zeros divided by //negative number with // least absolute value. prod = prod / max_neg; } return prod; } // Driver Code public static void main(String[] args) { int a[] = {-1, -1, -2, 4, 3}; int n = a.length; System.out.println(maxProductSubset(a, n)); }}/* This JAVA code is contributed by Rajput-Ji*/ # Python3 program to find maximum product# of a subset. def maxProductSubset(a, n): if n == 1: return a[0] # Find count of negative numbers, count # of zeros, negative number # with least absolute value # and product of non-zero numbers max_neg = -999999999999 count_neg = 0 count_zero = 0 prod = 1 for i in range(n): # If number is 0, we don't # multiply it with product. if a[i] == 0: count_zero += 1 continue # Count negatives and keep # track of negative number # with least absolute value. if a[i] < 0: count_neg += 1 max_neg = max(max_neg, a[i]) prod = prod * a[i] # If there are all zeros if count_zero == n: return 0 # If there are odd number of # negative numbers if count_neg & 1: # Exceptional case: There is only # negative and all other are zeros if (count_neg == 1 and count_zero > 0 and count_zero + count_neg == n): return 0 # Otherwise result is product of # all non-zeros divided # by negative number # with least absolute value prod = int(prod / max_neg) return prod # Driver Codeif __name__ == '__main__': a = [ -1, -1, -2, 4, 3 ] n = len(a) print(maxProductSubset(a, n)) # This code is contributed by PranchalK // C# Java program to find maximum// product of a subset.using System; class GFG{ static int maxProductSubset(int []a, int n){ if (n == 1) { return a[0]; } // Find count of negative numbers, // count of zeros, negative number with // least absolute value and product of // non-zero numbers int max_neg = int.MinValue; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number with // least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.Max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) { return 0; } // If there are odd number of // negative numbers if (count_neg % 2 == 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) { return 0; } // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. prod = prod / max_neg; } return prod;} // Driver codepublic static void Main(){ int []a = {-1, -1, -2, 4, 3}; int n = a.Length; Console.Write(maxProductSubset(a, n));}} // This code is contributed by Rajput-Ji <?php// PHP program to find maximum// product of a subset. function maxProductSubset($a, $n){ if ($n == 1) return $a[0]; // Find count of negative numbers, // count of zeros, negative number // with least absolute value and product of // non-zero numbers $max_neg = PHP_INT_MIN; $count_neg = 0; $count_zero = 0; $prod = 1; for ($i = 0; $i < $n; $i++) { // If number is 0, we don't // multiply it with product. if ($a[$i] == 0) { $count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if ($a[$i] < 0) { $count_neg++; $max_neg = max($max_neg, $a[$i]); } $prod = $prod * $a[$i]; } // If there are all zeros if ($count_zero == $n) return 0; // If there are odd number of // negative numbers if ($count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if ($count_neg == 1 && $count_zero > 0 && $count_zero + $count_neg == $n) return 0; // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. $prod = $prod / $max_neg; } return $prod;} // Driver Code$a = array(-1, -1, -2, 4, 3 );$n = sizeof($a);echo maxProductSubset($a, $n); // This code is contributed// by Akanksha Rai?> <script> // JavaScript program to find maximum// product of a subset. function maxProductSubset(a, n){ if (n == 1) return a[0]; // Find count of negative numbers, // count of zeros, negative number // with least absolute value and product of // non-zero numbers let max_neg = Number.MIN_SAFE_INTEGER; let count_neg = 0; count_zero = 0; let prod = 1; for (let i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) return 0; // If there are odd number of // negative numbers if (count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) return 0; // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. prod = prod / max_neg; } return prod;} // Driver Codelet a = [-1, -1, -2, 4, 3 ];let n = a.length;document.write(maxProductSubset(a, n)); // This code is contributed// by _saurabh_jaiswal </script> 24 Time Complexity: O(n) Auxiliary Space: O(1) Rajput-Ji Akanksha_Rai PranchalKatiyar Himanshu Gupta 20 _saurabh_jaiswal Arrays Greedy Technical Scripter Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 25875, "s": 25847, "text": "\n18 Jun, 2021" }, { "code": null, "e": 26042, "s": 25875, "text": "Given an array a, we have to find maximum product possible with the subset of elements present in the array. The maximum product can be single element also.Examples: " }, { "code": null, "e": 26280, "s": 26042, "text": "Input: a[] = { -1, -1, -2, 4, 3 }\nOutput: 24\nExplanation : Maximum product will be ( -2 * -1 * 4 * 3 ) = 24\n\nInput: a[] = { -1, 0 }\nOutput: 0\nExplanation: 0(single element) is maximum product possible\n \nInput: a[] = { 0, 0, 0 }\nOutput: 0" }, { "code": null, "e": 26427, "s": 26280, "text": "A simple solution is to generate all subsets, find product of every subset and return maximum product.A better solution is to use the below facts." }, { "code": null, "e": 26864, "s": 26427, "text": "If there are even number of negative numbers and no zeros, result is simply product of allIf there are odd number of negative numbers and no zeros, result is product of all except the negative integer with the least absolute value.If there are zeros, result is product of all except these zeros with one exceptional case. The exceptional case is when there is one negative number and all other elements are 0. In this case, result is 0." }, { "code": null, "e": 26955, "s": 26864, "text": "If there are even number of negative numbers and no zeros, result is simply product of all" }, { "code": null, "e": 27097, "s": 26955, "text": "If there are odd number of negative numbers and no zeros, result is product of all except the negative integer with the least absolute value." }, { "code": null, "e": 27303, "s": 27097, "text": "If there are zeros, result is product of all except these zeros with one exceptional case. The exceptional case is when there is one negative number and all other elements are 0. In this case, result is 0." }, { "code": null, "e": 27355, "s": 27303, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27359, "s": 27355, "text": "C++" }, { "code": null, "e": 27364, "s": 27359, "text": "Java" }, { "code": null, "e": 27372, "s": 27364, "text": "Python3" }, { "code": null, "e": 27375, "s": 27372, "text": "C#" }, { "code": null, "e": 27379, "s": 27375, "text": "PHP" }, { "code": null, "e": 27390, "s": 27379, "text": "Javascript" }, { "code": "// CPP program to find maximum product of// a subset.#include <bits/stdc++.h>using namespace std; int maxProductSubset(int a[], int n){ if (n == 1) return a[0]; // Find count of negative numbers, count // of zeros, negative number // with least absolute value // and product of non-zero numbers int max_neg = INT_MIN; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value if (a[i] < 0) { count_neg++; max_neg = max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) return 0; // If there are odd number of // negative numbers if (count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) return 0; // Otherwise result is product of // all non-zeros divided by //negative number with // least absolute value prod = prod / max_neg; } return prod;} // Driver Codeint main(){ int a[] = { -1, -1, -2, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); cout << maxProductSubset(a, n); return 0;}", "e": 28907, "s": 27390, "text": null }, { "code": "// Java program to find maximum product of// a subset. class GFG { static int maxProductSubset(int a[], int n) { if (n == 1) { return a[0]; } // Find count of negative numbers, count // of zeros, negative number // with least absolute value // and product of non-zero numbers int max_neg = Integer.MIN_VALUE; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) { return 0; } // If there are odd number of // negative numbers if (count_neg % 2 == 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) { return 0; } // Otherwise result is product of // all non-zeros divided by //negative number with // least absolute value. prod = prod / max_neg; } return prod; } // Driver Code public static void main(String[] args) { int a[] = {-1, -1, -2, 4, 3}; int n = a.length; System.out.println(maxProductSubset(a, n)); }}/* This JAVA code is contributed by Rajput-Ji*/", "e": 30733, "s": 28907, "text": null }, { "code": "# Python3 program to find maximum product# of a subset. def maxProductSubset(a, n): if n == 1: return a[0] # Find count of negative numbers, count # of zeros, negative number # with least absolute value # and product of non-zero numbers max_neg = -999999999999 count_neg = 0 count_zero = 0 prod = 1 for i in range(n): # If number is 0, we don't # multiply it with product. if a[i] == 0: count_zero += 1 continue # Count negatives and keep # track of negative number # with least absolute value. if a[i] < 0: count_neg += 1 max_neg = max(max_neg, a[i]) prod = prod * a[i] # If there are all zeros if count_zero == n: return 0 # If there are odd number of # negative numbers if count_neg & 1: # Exceptional case: There is only # negative and all other are zeros if (count_neg == 1 and count_zero > 0 and count_zero + count_neg == n): return 0 # Otherwise result is product of # all non-zeros divided # by negative number # with least absolute value prod = int(prod / max_neg) return prod # Driver Codeif __name__ == '__main__': a = [ -1, -1, -2, 4, 3 ] n = len(a) print(maxProductSubset(a, n)) # This code is contributed by PranchalK", "e": 32123, "s": 30733, "text": null }, { "code": "// C# Java program to find maximum// product of a subset.using System; class GFG{ static int maxProductSubset(int []a, int n){ if (n == 1) { return a[0]; } // Find count of negative numbers, // count of zeros, negative number with // least absolute value and product of // non-zero numbers int max_neg = int.MinValue; int count_neg = 0, count_zero = 0; int prod = 1; for (int i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number with // least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.Max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) { return 0; } // If there are odd number of // negative numbers if (count_neg % 2 == 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) { return 0; } // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. prod = prod / max_neg; } return prod;} // Driver codepublic static void Main(){ int []a = {-1, -1, -2, 4, 3}; int n = a.Length; Console.Write(maxProductSubset(a, n));}} // This code is contributed by Rajput-Ji", "e": 33764, "s": 32123, "text": null }, { "code": "<?php// PHP program to find maximum// product of a subset. function maxProductSubset($a, $n){ if ($n == 1) return $a[0]; // Find count of negative numbers, // count of zeros, negative number // with least absolute value and product of // non-zero numbers $max_neg = PHP_INT_MIN; $count_neg = 0; $count_zero = 0; $prod = 1; for ($i = 0; $i < $n; $i++) { // If number is 0, we don't // multiply it with product. if ($a[$i] == 0) { $count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if ($a[$i] < 0) { $count_neg++; $max_neg = max($max_neg, $a[$i]); } $prod = $prod * $a[$i]; } // If there are all zeros if ($count_zero == $n) return 0; // If there are odd number of // negative numbers if ($count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if ($count_neg == 1 && $count_zero > 0 && $count_zero + $count_neg == $n) return 0; // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. $prod = $prod / $max_neg; } return $prod;} // Driver Code$a = array(-1, -1, -2, 4, 3 );$n = sizeof($a);echo maxProductSubset($a, $n); // This code is contributed// by Akanksha Rai?>", "e": 35266, "s": 33764, "text": null }, { "code": "<script> // JavaScript program to find maximum// product of a subset. function maxProductSubset(a, n){ if (n == 1) return a[0]; // Find count of negative numbers, // count of zeros, negative number // with least absolute value and product of // non-zero numbers let max_neg = Number.MIN_SAFE_INTEGER; let count_neg = 0; count_zero = 0; let prod = 1; for (let i = 0; i < n; i++) { // If number is 0, we don't // multiply it with product. if (a[i] == 0) { count_zero++; continue; } // Count negatives and keep // track of negative number // with least absolute value. if (a[i] < 0) { count_neg++; max_neg = Math.max(max_neg, a[i]); } prod = prod * a[i]; } // If there are all zeros if (count_zero == n) return 0; // If there are odd number of // negative numbers if (count_neg & 1) { // Exceptional case: There is only // negative and all other are zeros if (count_neg == 1 && count_zero > 0 && count_zero + count_neg == n) return 0; // Otherwise result is product of // all non-zeros divided by negative // number with least absolute value. prod = prod / max_neg; } return prod;} // Driver Codelet a = [-1, -1, -2, 4, 3 ];let n = a.length;document.write(maxProductSubset(a, n)); // This code is contributed// by _saurabh_jaiswal </script>", "e": 36794, "s": 35266, "text": null }, { "code": null, "e": 36797, "s": 36794, "text": "24" }, { "code": null, "e": 36842, "s": 36797, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 36852, "s": 36842, "text": "Rajput-Ji" }, { "code": null, "e": 36865, "s": 36852, "text": "Akanksha_Rai" }, { "code": null, "e": 36881, "s": 36865, "text": "PranchalKatiyar" }, { "code": null, "e": 36899, "s": 36881, "text": "Himanshu Gupta 20" }, { "code": null, "e": 36916, "s": 36899, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36923, "s": 36916, "text": "Arrays" }, { "code": null, "e": 36930, "s": 36923, "text": "Greedy" }, { "code": null, "e": 36949, "s": 36930, "text": "Technical Scripter" }, { "code": null, "e": 36956, "s": 36949, "text": "Arrays" }, { "code": null, "e": 36963, "s": 36956, "text": "Greedy" }, { "code": null, "e": 37061, "s": 36963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37129, "s": 37061, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37173, "s": 37129, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37221, "s": 37173, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 37244, "s": 37221, "text": "Introduction to Arrays" }, { "code": null, "e": 37276, "s": 37244, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37327, "s": 37276, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 37385, "s": 37327, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 37436, "s": 37385, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 37496, "s": 37436, "text": "Write a program to print all permutations of a given string" } ]
Java Basic Syntax - GeeksforGeeks
24 Feb, 2022 A Java program is a collection of objects, and these objects communicate through method calls to each other to work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and semantics of Java. Basic terminologies in Java 1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a template which describes the data and behaviour associated with its instance. Example: Blueprint of the house is class. 2. Object: The object is an instance of a class. It is an entity which has behaviour and state. Example: A car is an object whose states are: brand, colour, number-plate. Behaviour: Running on the road. 3. Method: The behaviour of an object is the method. Example: The fuel indicator indicates the amount of fuel left in the car. 4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables. Example: Steps to compile and run a java program in a console javac GFG.java java GFG Java public class GFG { public static void main (String[] args) { System.out.println("GFG!"); }} GFG! Note: When the class is public, the name of the file has to be the class name. The Basic Syntax: 1. Comments in Java There are three types of comments in Java. i. Single line Comment // System.out.println("GFG!"); ii. Multi-line Comment /* System.out.println("GFG!"); System.out.println("Alice!"); */ iii. Documentation Comment. Also called a doc comment. /** documentation */ 2. Source File Name The name of a source file should exactly match the public class name with the extension of .java. The name of the file can be a different name if it does not have any public class. Assume you have a public class GFG. GFG.java // valid syntax gfg.java // invalid syntax 3. Case Sensitivity Java is a case-sensitive language, which means that the identifiers AB, Ab, aB, and ab are different in Java. System.out.println("Alice"); // valid syntax system.out.println("Alice"); // invalid syntax 4. Class Names i. The first letter of the class should be in Uppercase (lowercase is allowed, but not discouraged). ii. If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because the are used for a special purpose (for inner and anonymous classes). class MyJavaProgram // valid syntax class 1Program // invalid syntax class My1Program // valid syntax class $Program // valid syntax, but discouraged class My$Program // valid syntax, but discouraged (inner class Program inside the class My) class myJavaProgram // valid syntax, but discouraged 5. public static void main(String [] args) The method main() is the main entry point into a Java program; this is where the processing starts. Also allowed is the signature public static void main(String... args). 6. Method Names i. All the method names should start with a lowercase letter. ii. If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols. public void employeeRecords() // valid syntax public void EmployeeRecords() // valid syntax, but discouraged 7. Identifiers in java Identifiers are the names of local variables, instance and class variables, labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset. i. All identifiers can begin with a letter, a currency symbol or an underscore (_). According to the convention, a letter should be lower case for variables. ii. The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters. iii. Most importantly identifiers are case-sensitive. iv. A keyword cannot be used as an identifier since it is a reserved word and has some special meaning. Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value Illegal identifiers: 74ak, -amount 8. White-spaces in Java A line containing only white-spaces, possibly with the comment, is known as a blank line, and the Java compiler totally ignores it. 9. Access Modifiers: These modifiers control the scope of class and methods. Access Modifiers: default, public, protected, private Non-access Modifiers: final, abstract, strictfp 10. Java Keywords 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 variable names or objects. ashish1994mishra shrestha499 tquadratdo java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Stream In Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java Generics in Java
[ { "code": null, "e": 30195, "s": 30167, "text": "\n24 Feb, 2022" }, { "code": null, "e": 30435, "s": 30195, "text": "A Java program is a collection of objects, and these objects communicate through method calls to each other to work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and semantics of Java." }, { "code": null, "e": 30463, "s": 30435, "text": "Basic terminologies in Java" }, { "code": null, "e": 30643, "s": 30463, "text": "1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a template which describes the data and behaviour associated with its instance." }, { "code": null, "e": 30685, "s": 30643, "text": "Example: Blueprint of the house is class." }, { "code": null, "e": 30781, "s": 30685, "text": "2. Object: The object is an instance of a class. It is an entity which has behaviour and state." }, { "code": null, "e": 30856, "s": 30781, "text": "Example: A car is an object whose states are: brand, colour, number-plate." }, { "code": null, "e": 30888, "s": 30856, "text": "Behaviour: Running on the road." }, { "code": null, "e": 30941, "s": 30888, "text": "3. Method: The behaviour of an object is the method." }, { "code": null, "e": 31015, "s": 30941, "text": "Example: The fuel indicator indicates the amount of fuel left in the car." }, { "code": null, "e": 31202, "s": 31015, "text": "4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables." }, { "code": null, "e": 31264, "s": 31202, "text": "Example: Steps to compile and run a java program in a console" }, { "code": null, "e": 31288, "s": 31264, "text": "javac GFG.java\njava GFG" }, { "code": null, "e": 31293, "s": 31288, "text": "Java" }, { "code": "public class GFG { public static void main (String[] args) { System.out.println(\"GFG!\"); }}", "e": 31397, "s": 31293, "text": null }, { "code": null, "e": 31402, "s": 31397, "text": "GFG!" }, { "code": null, "e": 31481, "s": 31402, "text": "Note: When the class is public, the name of the file has to be the class name." }, { "code": null, "e": 31499, "s": 31481, "text": "The Basic Syntax:" }, { "code": null, "e": 31519, "s": 31499, "text": "1. Comments in Java" }, { "code": null, "e": 31563, "s": 31519, "text": "There are three types of comments in Java. " }, { "code": null, "e": 31587, "s": 31563, "text": " i. Single line Comment" }, { "code": null, "e": 31618, "s": 31587, "text": "// System.out.println(\"GFG!\");" }, { "code": null, "e": 31641, "s": 31618, "text": "ii. Multi-line Comment" }, { "code": null, "e": 31713, "s": 31641, "text": "/*\n System.out.println(\"GFG!\");\n System.out.println(\"Alice!\");\n*/" }, { "code": null, "e": 31768, "s": 31713, "text": "iii. Documentation Comment. Also called a doc comment." }, { "code": null, "e": 31789, "s": 31768, "text": "/** documentation */" }, { "code": null, "e": 31809, "s": 31789, "text": "2. Source File Name" }, { "code": null, "e": 32026, "s": 31809, "text": "The name of a source file should exactly match the public class name with the extension of .java. The name of the file can be a different name if it does not have any public class. Assume you have a public class GFG." }, { "code": null, "e": 32078, "s": 32026, "text": "GFG.java // valid syntax\ngfg.java // invalid syntax" }, { "code": null, "e": 32098, "s": 32078, "text": "3. Case Sensitivity" }, { "code": null, "e": 32208, "s": 32098, "text": "Java is a case-sensitive language, which means that the identifiers AB, Ab, aB, and ab are different in Java." }, { "code": null, "e": 32300, "s": 32208, "text": "System.out.println(\"Alice\"); // valid syntax\nsystem.out.println(\"Alice\"); // invalid syntax" }, { "code": null, "e": 32315, "s": 32300, "text": "4. Class Names" }, { "code": null, "e": 32416, "s": 32315, "text": "i. The first letter of the class should be in Uppercase (lowercase is allowed, but not discouraged)." }, { "code": null, "e": 32744, "s": 32416, "text": "ii. If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because the are used for a special purpose (for inner and anonymous classes)." }, { "code": null, "e": 33073, "s": 32744, "text": "class MyJavaProgram // valid syntax\nclass 1Program // invalid syntax\nclass My1Program // valid syntax\nclass $Program // valid syntax, but discouraged\nclass My$Program // valid syntax, but discouraged (inner class Program inside the class My)\nclass myJavaProgram // valid syntax, but discouraged" }, { "code": null, "e": 33116, "s": 33073, "text": "5. public static void main(String [] args)" }, { "code": null, "e": 33287, "s": 33116, "text": "The method main() is the main entry point into a Java program; this is where the processing starts. Also allowed is the signature public static void main(String... args)." }, { "code": null, "e": 33303, "s": 33287, "text": "6. Method Names" }, { "code": null, "e": 33365, "s": 33303, "text": "i. All the method names should start with a lowercase letter." }, { "code": null, "e": 33584, "s": 33365, "text": "ii. If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols." }, { "code": null, "e": 33693, "s": 33584, "text": "public void employeeRecords() // valid syntax\npublic void EmployeeRecords() // valid syntax, but discouraged" }, { "code": null, "e": 33716, "s": 33693, "text": "7. Identifiers in java" }, { "code": null, "e": 33925, "s": 33716, "text": "Identifiers are the names of local variables, instance and class variables, labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset. " }, { "code": null, "e": 34083, "s": 33925, "text": "i. All identifiers can begin with a letter, a currency symbol or an underscore (_). According to the convention, a letter should be lower case for variables." }, { "code": null, "e": 34358, "s": 34083, "text": "ii. The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters." }, { "code": null, "e": 34412, "s": 34358, "text": "iii. Most importantly identifiers are case-sensitive." }, { "code": null, "e": 34516, "s": 34412, "text": "iv. A keyword cannot be used as an identifier since it is a reserved word and has some special meaning." }, { "code": null, "e": 34629, "s": 34516, "text": "Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value\nIllegal identifiers: 74ak, -amount" }, { "code": null, "e": 34653, "s": 34629, "text": "8. White-spaces in Java" }, { "code": null, "e": 34785, "s": 34653, "text": "A line containing only white-spaces, possibly with the comment, is known as a blank line, and the Java compiler totally ignores it." }, { "code": null, "e": 34862, "s": 34785, "text": "9. Access Modifiers: These modifiers control the scope of class and methods." }, { "code": null, "e": 34916, "s": 34862, "text": "Access Modifiers: default, public, protected, private" }, { "code": null, "e": 34964, "s": 34916, "text": "Non-access Modifiers: final, abstract, strictfp" }, { "code": null, "e": 34982, "s": 34964, "text": "10. Java Keywords" }, { "code": null, "e": 35191, "s": 34982, "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 variable names or objects. " }, { "code": null, "e": 35208, "s": 35191, "text": "ashish1994mishra" }, { "code": null, "e": 35220, "s": 35208, "text": "shrestha499" }, { "code": null, "e": 35231, "s": 35220, "text": "tquadratdo" }, { "code": null, "e": 35243, "s": 35231, "text": "java-basics" }, { "code": null, "e": 35248, "s": 35243, "text": "Java" }, { "code": null, "e": 35253, "s": 35248, "text": "Java" }, { "code": null, "e": 35351, "s": 35253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35395, "s": 35351, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35431, "s": 35395, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 35456, "s": 35431, "text": "Reverse a string in Java" }, { "code": null, "e": 35471, "s": 35456, "text": "Stream In Java" }, { "code": null, "e": 35502, "s": 35471, "text": "How to iterate any Map in Java" }, { "code": null, "e": 35534, "s": 35502, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 35558, "s": 35534, "text": "Singleton Class in Java" }, { "code": null, "e": 35586, "s": 35558, "text": "Initializing a List in Java" }, { "code": null, "e": 35632, "s": 35586, "text": "Different ways of Reading a text file in Java" } ]
Perl | Operators | Set - 1 - GeeksforGeeks
15 Sep, 2021 Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Ternary Operator Arithmetic Operators These are used to perform arithmetic/mathematical operations on operands. Addition: ‘+‘ operator is used to add the values of the two operands. For Example: $a = 5; $b = 10; print $a + $b; Here Result will be 15 Subtraction: ‘–‘ operator is used to subtract right hand operand from left hand operand. For Example: $a = 10; $b = 5; print $a - $b; Here Result will be 5 Multiplication: ‘*‘ operator is used to multiplies the value on either side of the operator. For Example: $a = 5; $b = 10; print $a * $b; Here Result will be 50 Division Operator: ‘/‘ operator returns the remainder when first operand is divided by the second. For Example: $a = 30; $b = 15; print $a / $b; Here Result will be 3 Modulus Operator: ‘%‘ operator is used to divide left hand operand from right operand and returns remainder. For Example: $a = 10; $b = 15; print $a % $b; Here Result will be 5 Exponent Operator: ‘**‘ operator is used to perform the exponential(power) calculation on operands. For Example: $a = 2; $b = 3; print $a**$b; Here Result will be 8 Program: To demonstrate the arithmetic operators Perl # Perl Program to illustrate the Arithmetic Operators # Operands$a = 10;$b = 4; # using arithmetic operatorsprint "Addition is: ", $a + $b, "\n";print "Subtraction is: ", $a - $b, "\n" ;print "Multiplication is: ", $a * $b, "\n";print "Division is: ", $a / $b, "\n";print "Modulus is: ", $a % $b, "\n";print "Exponent is: ", $a ** $b, "\n"; Output: Addition is: 14 Subtraction is: 6 Multiplication is: 40 Division is: 2.5 Modulus is: 2 Exponent is: 10000 Relational Operators Relational operators are used for comparison of two values. These operators will return either 1(true) or nothing(i.e. 0(false)). Sometimes these operators are also termed as the Equality Operators. These operators have the different symbols to operate on strings. To know about Comparison Operators operation on String you can refer to this. Equal To Operator: ‘==’ Check if two values are equal or not. If equals then return 1 otherwise return nothing. Not equal To Operator: ‘!=’ Check if the two values are equal or not. If not equal then returns 1 otherwise returns nothing. Comparison of equal to Operator: ‘< = >’ If left operand is less than right then returns -1, if equal returns 0 else returns 1. Greater than Operator: ‘>’ If left operand is greater than right returns 1 else returns nothing. Less than Operator: ‘<‘ If left operand is lesser than right returns 1 else returns nothing. Greater than equal to Operator: ‘>=’ If left operand is greater than or equal to right returns 1 else returns nothing. Less than equal to Operator: ‘<=’ If left operand is lesser than or equal to right returns 1 else returns nothing. Program: To illustrate the Relational Operators in Perl Perl # Perl Program to illustrate the Relational Operators # Operands$a = 10;$b = 60; # using Relational Operatorsif ($a == $b){ print "Equal To Operator is True\n";}else{ print "Equal To Operator is False\n";} if ($a != $b){ print "Not Equal To Operator is True\n";}else{ print "Not Equal To Operator is False\n";} if ($a > $b){ print "Greater Than Operator is True\n";}else{ print "Greater Than Operator is False\n";} if ($a < $b){ print "Less Than Operator is True\n";}else{ print "Less Than Operator is False\n";} if ($a >= $b){ print "Greater Than Equal To Operator is True\n";}else{ print "Greater Than Equal To Operator is False\n";} if ($a <= $b){ print "Less Than Equal To Operator is True\n";}else{ print "Less Than Equal To Operator is False\n";}if ($a <=> $b){ print "Comparison of Operator is True\n";}else{ print "Comparison of Operator is False\n";} Output: Equal To Operator is False Not Equal To Operator is True Greater Than Operator is False Less Than Operator is True Greater Than Equal To Operator is False Less Than Equal To Operator is True Comparison of Operator is True Logical Operators These operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. Logical AND: The ‘and’ operator returns true when both the conditions in consideration are satisfied. For example, $a and $b is true when both a and b both are true (i.e. non-zero). You can use also &&. Logical OR: The ‘or’ operator returns true when one (or both) of the conditions in consideration is satisfied. For example, $a or $b is true if one of a or b is true (i.e. non-zero). Of course, it gives result “true” when both a and b are true. You can use also || Logical NOT: The ‘not’ operator will give 1 if the condition in consideration is satisfied. For example, not($d) is true if $d is 0. Program: To demonstrate the working of Logical Operators: Perl # Perl Program to illustrate the Logical Operators # Operands$a = true;$b = false; # AND operator$result = $a && $b;print "AND Operator: ", $result,"\n"; # OR operator$result = $a || $b;print "OR Operator: ", $result,"\n"; # NOT operator$d = 0;$result = not($d);print "NOT Operator: ", $result; Output: AND Operator: false OR Operator: true NOT Operator: 1 Bitwise Operators These operators are used to perform the bitwise operation. It will first convert the number into bits and perform the bit-level operation on the operands. & (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. For example $a = 13; // 1101 $b = 5; // 0101 $c = $b & $a; print $c; Here Output will be 5 Explanation: $a = 1 1 0 1 $b = 0 1 0 1 --------------- $c = 0 1 0 1 --------------- | (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1. For example $a = 13; // 1101 $b = 5; // 0101 $c = $b | $a; print $c; Here Output will be 13 Explanation: $a = 1 1 0 1 $b = 0 1 0 1 --------------- $c = 1 1 0 1 --------------- ^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. For example $a = 13; // 1101 $b = 5; // 0101 $c = $b ^ $a; print $c; Here Output will be 9 Explanation: $a = 1 1 0 1 $b = 0 1 0 1 ------------- $c = 1 0 0 1 ------------- ~ (Complement Operator) This is unary operator act as flipping bits. It’s work is to reverse the bits and gives result using 2’s complement form due to a signed binary number. (<<) Binary Left Shift Operator will takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. It performs multiplication of the left operand by the number of times specified by the right operand. For Example: $a = 60; $c = $a << 2; print $c; Output: 240 Explanation: 60 * 2 = 120 ---(1) 120 * 2 = 240 ---(2) (>>)Binary Right Shift Operator will take two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. It performs division of the left operand by the number of times specified by right operand. For Example: $a = 60; $c = $a >> 2; print $c; Output: 15 Explanation: 60 / 2 = 30 ---(1) 30 / 2 = 15 ---(2) Program: To demonstrate the working of bitwise operators: Perl # Perl Program to illustrate the Bitwise operators#!/usr/local/bin/perluse integer; # Operands$a = 80;$b = 2; # Bitwise AND Operator$result = $a & $b;print "Bitwise AND: ", $result, "\n"; # Bitwise OR Operator$result = $a | $b;print "Bitwise OR: ", $result, "\n"; # Bitwise XOR Operator$result = $a ^ $b;print "Bitwise XOR: ", $result, "\n"; # Bitwise Complement Operator$result = ~$a;print "Bitwise Complement: ", $result, "\n"; # Bitwise Left Shift Operator$result = $a << $b;print "Bitwise Left Shift: ", $result, "\n"; # Bitwise Right Shift Operator$result = $a >> $b;print "Bitwise Right Shift: ", $result, "\n"; Output: Bitwise AND: 0 Bitwise OR: 82 Bitwise XOR: 82 Bitwise Complement: -81 Bitwise Left Shift: 320 Bitwise Right Shift: 20 Assignment Operators Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. Different types of assignment operators are shown below: “=”(Simple Assignment) : This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example : $a = 10; $b = 20; “+=”(Add Assignment) : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example : ($a += $b) can be written as ($a = $a + $b) If initially value stored in a is 5. Then ($a += 6) = 11. “-=”(Subtract Assignment) : This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. Example : ($a -= $b) can be written as ($a = $a - $b) If initially value stored in a is 8. Then ($a -= 6) = 2. “*=”(Multiply Assignment) : This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example : ($a *= $b) can be written as ($a = $a * $b) If initially value stored in a is 5. Then ($a *= 6) = 30. “/=”(Division Assignment) : This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example : ($a /= $b) can be written as ($a = $a / $b) If initially value stored in a is 6. Then ($a /= 2) = 3. “%=”(Modulus Assignment) : This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example : ($a %= $b) can be written as ($a = $a % $b) If initially value stored in a is 6. Then ($a %= 2) = 0. “**=”(Exponent Assignment) : This operator is combination of ‘**’ and ‘=’ operators. This operator first exponent the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example : ($a **= $b) can be written as ($a = $a ** $b) If initially, value stored in a is 6. Then ($a **= 2) = 36. Program: To demonstrate the working of Assignment Operators Perl # Perl program to demonstrate the working# of Assignment Operators#!/usr/local/bin/perl # taking two variables & using# simple assignments operation$a = 8;$b = 5; # using Assignment Operatorsprint "Addition Assignment Operator: ", $a += $b, "\n"; $a = 8;$b = 4;print "Subtraction Assignment Operator: ", $a -= $b, "\n" ; $a = 8;$b = 4;print "Multiplication Assignment Operator: ", $a*=$b, "\n"; $a = 8;$b = 4;print "Division Assignment Operator: ",$a/=$b, "\n"; $a = 8;$b = 5;print "Modulo Assignment Operator: ", $a%=$b,"\n"; $a = 8;$b = 4;print "Exponent Assignment Operator: ", $a**=$b, "\n"; Output: Addition Assignment Operator: 13 Subtraction Assignment Operator: 4 Multiplication Assignment Operator: 32 Division Assignment Operator: 2 Modulo Assignment Operator: 3 Exponent Assignment Operator: 4096 Ternary Operator It is a conditional operator which is a shorthand version of if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression. Syntax: condition ? first_expression : second_expression; Explanation: condition: It must be evaluated to true or false. If the condition is true first_expression is evaluated and becomes the result. If the condition is false, second_expression is evaluated and becomes the result. Example: Perl # Perl program to demonstrate the working# of Ternary Operator $x = 5;$y = 10; # To find which value is greater# Using Ternary Operator$result = $x > $y ? $x : $y; # displaying the outputprint "The Larger Number is: $result" Output: The Larger Number is: 10 Note: In the Ternary operator the condition can be any expression also which can make by using the different operators like relational operators, logical operators, etc. Example: Perl # Perl program to demonstrate the working# of Ternary Operator by using expression# as the condition # here maximum value can be 100$MAX_VALUE = 100; # suppose user provide value$user_value = 444; # To find which whether user provided# value is satisfying the maximum value# or not by using Ternary Operator$result = $user_value <= $MAX_VALUE ? $user_value : $MAX_VALUE; # displaying the output# Here it will be MAX_VALUEprint "$result" Output: 100 Akanksha_Rai Code_Mech simranarora5sos simmytarika5 perl-basics perl-operators Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | grep() Function Perl | substr() function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | Removing leading and trailing white spaces (trim) Use of print() and say() in Perl Perl | length() Function
[ { "code": null, "e": 26525, "s": 26497, "text": "\n15 Sep, 2021" }, { "code": null, "e": 26850, "s": 26525, "text": "Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality:" }, { "code": null, "e": 26871, "s": 26850, "text": "Arithmetic Operators" }, { "code": null, "e": 26892, "s": 26871, "text": "Relational Operators" }, { "code": null, "e": 26910, "s": 26892, "text": "Logical Operators" }, { "code": null, "e": 26928, "s": 26910, "text": "Bitwise Operators" }, { "code": null, "e": 26949, "s": 26928, "text": "Assignment Operators" }, { "code": null, "e": 26966, "s": 26949, "text": "Ternary Operator" }, { "code": null, "e": 26987, "s": 26966, "text": "Arithmetic Operators" }, { "code": null, "e": 27062, "s": 26987, "text": "These are used to perform arithmetic/mathematical operations on operands. " }, { "code": null, "e": 27145, "s": 27062, "text": "Addition: ‘+‘ operator is used to add the values of the two operands. For Example:" }, { "code": null, "e": 27200, "s": 27145, "text": "$a = 5;\n$b = 10;\nprint $a + $b;\nHere Result will be 15" }, { "code": null, "e": 27302, "s": 27200, "text": "Subtraction: ‘–‘ operator is used to subtract right hand operand from left hand operand. For Example:" }, { "code": null, "e": 27356, "s": 27302, "text": "$a = 10;\n$b = 5;\nprint $a - $b;\nHere Result will be 5" }, { "code": null, "e": 27462, "s": 27356, "text": "Multiplication: ‘*‘ operator is used to multiplies the value on either side of the operator. For Example:" }, { "code": null, "e": 27517, "s": 27462, "text": "$a = 5;\n$b = 10;\nprint $a * $b;\nHere Result will be 50" }, { "code": null, "e": 27629, "s": 27517, "text": "Division Operator: ‘/‘ operator returns the remainder when first operand is divided by the second. For Example:" }, { "code": null, "e": 27684, "s": 27629, "text": "$a = 30;\n$b = 15;\nprint $a / $b;\nHere Result will be 3" }, { "code": null, "e": 27806, "s": 27684, "text": "Modulus Operator: ‘%‘ operator is used to divide left hand operand from right operand and returns remainder. For Example:" }, { "code": null, "e": 27861, "s": 27806, "text": "$a = 10;\n$b = 15;\nprint $a % $b;\nHere Result will be 5" }, { "code": null, "e": 27974, "s": 27861, "text": "Exponent Operator: ‘**‘ operator is used to perform the exponential(power) calculation on operands. For Example:" }, { "code": null, "e": 28026, "s": 27974, "text": "$a = 2;\n$b = 3;\nprint $a**$b;\nHere Result will be 8" }, { "code": null, "e": 28075, "s": 28026, "text": "Program: To demonstrate the arithmetic operators" }, { "code": null, "e": 28080, "s": 28075, "text": "Perl" }, { "code": "# Perl Program to illustrate the Arithmetic Operators # Operands$a = 10;$b = 4; # using arithmetic operatorsprint \"Addition is: \", $a + $b, \"\\n\";print \"Subtraction is: \", $a - $b, \"\\n\" ;print \"Multiplication is: \", $a * $b, \"\\n\";print \"Division is: \", $a / $b, \"\\n\";print \"Modulus is: \", $a % $b, \"\\n\";print \"Exponent is: \", $a ** $b, \"\\n\";", "e": 28421, "s": 28080, "text": null }, { "code": null, "e": 28429, "s": 28421, "text": "Output:" }, { "code": null, "e": 28535, "s": 28429, "text": "Addition is: 14\nSubtraction is: 6\nMultiplication is: 40\nDivision is: 2.5\nModulus is: 2\nExponent is: 10000" }, { "code": null, "e": 28556, "s": 28535, "text": "Relational Operators" }, { "code": null, "e": 28900, "s": 28556, "text": "Relational operators are used for comparison of two values. These operators will return either 1(true) or nothing(i.e. 0(false)). Sometimes these operators are also termed as the Equality Operators. These operators have the different symbols to operate on strings. To know about Comparison Operators operation on String you can refer to this. " }, { "code": null, "e": 29012, "s": 28900, "text": "Equal To Operator: ‘==’ Check if two values are equal or not. If equals then return 1 otherwise return nothing." }, { "code": null, "e": 29137, "s": 29012, "text": "Not equal To Operator: ‘!=’ Check if the two values are equal or not. If not equal then returns 1 otherwise returns nothing." }, { "code": null, "e": 29265, "s": 29137, "text": "Comparison of equal to Operator: ‘< = >’ If left operand is less than right then returns -1, if equal returns 0 else returns 1." }, { "code": null, "e": 29362, "s": 29265, "text": "Greater than Operator: ‘>’ If left operand is greater than right returns 1 else returns nothing." }, { "code": null, "e": 29455, "s": 29362, "text": "Less than Operator: ‘<‘ If left operand is lesser than right returns 1 else returns nothing." }, { "code": null, "e": 29574, "s": 29455, "text": "Greater than equal to Operator: ‘>=’ If left operand is greater than or equal to right returns 1 else returns nothing." }, { "code": null, "e": 29689, "s": 29574, "text": "Less than equal to Operator: ‘<=’ If left operand is lesser than or equal to right returns 1 else returns nothing." }, { "code": null, "e": 29746, "s": 29689, "text": "Program: To illustrate the Relational Operators in Perl " }, { "code": null, "e": 29751, "s": 29746, "text": "Perl" }, { "code": "# Perl Program to illustrate the Relational Operators # Operands$a = 10;$b = 60; # using Relational Operatorsif ($a == $b){ print \"Equal To Operator is True\\n\";}else{ print \"Equal To Operator is False\\n\";} if ($a != $b){ print \"Not Equal To Operator is True\\n\";}else{ print \"Not Equal To Operator is False\\n\";} if ($a > $b){ print \"Greater Than Operator is True\\n\";}else{ print \"Greater Than Operator is False\\n\";} if ($a < $b){ print \"Less Than Operator is True\\n\";}else{ print \"Less Than Operator is False\\n\";} if ($a >= $b){ print \"Greater Than Equal To Operator is True\\n\";}else{ print \"Greater Than Equal To Operator is False\\n\";} if ($a <= $b){ print \"Less Than Equal To Operator is True\\n\";}else{ print \"Less Than Equal To Operator is False\\n\";}if ($a <=> $b){ print \"Comparison of Operator is True\\n\";}else{ print \"Comparison of Operator is False\\n\";}", "e": 30639, "s": 29751, "text": null }, { "code": null, "e": 30648, "s": 30639, "text": "Output: " }, { "code": null, "e": 30870, "s": 30648, "text": "Equal To Operator is False\nNot Equal To Operator is True\nGreater Than Operator is False\nLess Than Operator is True\nGreater Than Equal To Operator is False\nLess Than Equal To Operator is True\nComparison of Operator is True" }, { "code": null, "e": 30888, "s": 30870, "text": "Logical Operators" }, { "code": null, "e": 31035, "s": 30888, "text": "These operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration." }, { "code": null, "e": 31238, "s": 31035, "text": "Logical AND: The ‘and’ operator returns true when both the conditions in consideration are satisfied. For example, $a and $b is true when both a and b both are true (i.e. non-zero). You can use also &&." }, { "code": null, "e": 31503, "s": 31238, "text": "Logical OR: The ‘or’ operator returns true when one (or both) of the conditions in consideration is satisfied. For example, $a or $b is true if one of a or b is true (i.e. non-zero). Of course, it gives result “true” when both a and b are true. You can use also ||" }, { "code": null, "e": 31636, "s": 31503, "text": "Logical NOT: The ‘not’ operator will give 1 if the condition in consideration is satisfied. For example, not($d) is true if $d is 0." }, { "code": null, "e": 31696, "s": 31636, "text": "Program: To demonstrate the working of Logical Operators: " }, { "code": null, "e": 31701, "s": 31696, "text": "Perl" }, { "code": "# Perl Program to illustrate the Logical Operators # Operands$a = true;$b = false; # AND operator$result = $a && $b;print \"AND Operator: \", $result,\"\\n\"; # OR operator$result = $a || $b;print \"OR Operator: \", $result,\"\\n\"; # NOT operator$d = 0;$result = not($d);print \"NOT Operator: \", $result;", "e": 31998, "s": 31701, "text": null }, { "code": null, "e": 32007, "s": 31998, "text": "Output: " }, { "code": null, "e": 32061, "s": 32007, "text": "AND Operator: false\nOR Operator: true\nNOT Operator: 1" }, { "code": null, "e": 32079, "s": 32061, "text": "Bitwise Operators" }, { "code": null, "e": 32235, "s": 32079, "text": "These operators are used to perform the bitwise operation. It will first convert the number into bits and perform the bit-level operation on the operands. " }, { "code": null, "e": 32383, "s": 32235, "text": "& (bitwise AND) Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. For example" }, { "code": null, "e": 32558, "s": 32383, "text": "$a = 13; // 1101\n$b = 5; // 0101\n$c = $b & $a; \nprint $c;\nHere Output will be 5\n\nExplanation:\n\n$a = 1 1 0 1\n$b = 0 1 0 1\n---------------\n$c = 0 1 0 1\n---------------" }, { "code": null, "e": 32704, "s": 32558, "text": "| (bitwise OR) Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1. For example" }, { "code": null, "e": 32880, "s": 32704, "text": "$a = 13; // 1101\n$b = 5; // 0101\n$c = $b | $a; \nprint $c;\nHere Output will be 13\n\nExplanation:\n$a = 1 1 0 1\n$b = 0 1 0 1\n---------------\n$c = 1 1 0 1\n---------------" }, { "code": null, "e": 33034, "s": 32880, "text": "^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. For example" }, { "code": null, "e": 33197, "s": 33034, "text": "$a = 13; // 1101\n$b = 5; // 0101\n$c = $b ^ $a;\nprint $c;\nHere Output will be 9\n\nExplanation:\n$a = 1 1 0 1\n$b = 0 1 0 1\n-------------\n$c = 1 0 0 1\n-------------" }, { "code": null, "e": 33373, "s": 33197, "text": "~ (Complement Operator) This is unary operator act as flipping bits. It’s work is to reverse the bits and gives result using 2’s complement form due to a signed binary number." }, { "code": null, "e": 33645, "s": 33373, "text": "(<<) Binary Left Shift Operator will takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. It performs multiplication of the left operand by the number of times specified by the right operand. For Example:" }, { "code": null, "e": 33749, "s": 33645, "text": "$a = 60;\n$c = $a << 2;\nprint $c;\n\nOutput: 240\n\nExplanation:\n60 * 2 = 120 ---(1)\n120 * 2 = 240 ---(2)" }, { "code": null, "e": 34011, "s": 33749, "text": "(>>)Binary Right Shift Operator will take two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. It performs division of the left operand by the number of times specified by right operand. For Example:" }, { "code": null, "e": 34115, "s": 34011, "text": "$a = 60;\n$c = $a >> 2;\nprint $c;\nOutput: 15\n\nExplanation:\n60 / 2 = 30 ---(1)\n30 / 2 = 15 ---(2)" }, { "code": null, "e": 34174, "s": 34115, "text": "Program: To demonstrate the working of bitwise operators: " }, { "code": null, "e": 34179, "s": 34174, "text": "Perl" }, { "code": "# Perl Program to illustrate the Bitwise operators#!/usr/local/bin/perluse integer; # Operands$a = 80;$b = 2; # Bitwise AND Operator$result = $a & $b;print \"Bitwise AND: \", $result, \"\\n\"; # Bitwise OR Operator$result = $a | $b;print \"Bitwise OR: \", $result, \"\\n\"; # Bitwise XOR Operator$result = $a ^ $b;print \"Bitwise XOR: \", $result, \"\\n\"; # Bitwise Complement Operator$result = ~$a;print \"Bitwise Complement: \", $result, \"\\n\"; # Bitwise Left Shift Operator$result = $a << $b;print \"Bitwise Left Shift: \", $result, \"\\n\"; # Bitwise Right Shift Operator$result = $a >> $b;print \"Bitwise Right Shift: \", $result, \"\\n\";", "e": 34797, "s": 34179, "text": null }, { "code": null, "e": 34806, "s": 34797, "text": "Output: " }, { "code": null, "e": 34924, "s": 34806, "text": "Bitwise AND: 0\nBitwise OR: 82\nBitwise XOR: 82\nBitwise Complement: -81\nBitwise Left Shift: 320\nBitwise Right Shift: 20" }, { "code": null, "e": 34945, "s": 34924, "text": "Assignment Operators" }, { "code": null, "e": 35194, "s": 34945, "text": "Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. Different types of assignment operators are shown below: " }, { "code": null, "e": 35355, "s": 35194, "text": "“=”(Simple Assignment) : This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example :" }, { "code": null, "e": 35373, "s": 35355, "text": "$a = 10;\n$b = 20;" }, { "code": null, "e": 35611, "s": 35373, "text": "“+=”(Add Assignment) : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example :" }, { "code": null, "e": 35655, "s": 35611, "text": "($a += $b) can be written as ($a = $a + $b)" }, { "code": null, "e": 35713, "s": 35655, "text": "If initially value stored in a is 5. Then ($a += 6) = 11." }, { "code": null, "e": 35963, "s": 35713, "text": "“-=”(Subtract Assignment) : This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left. Example :" }, { "code": null, "e": 36007, "s": 35963, "text": "($a -= $b) can be written as ($a = $a - $b)" }, { "code": null, "e": 36064, "s": 36007, "text": "If initially value stored in a is 8. Then ($a -= 6) = 2." }, { "code": null, "e": 36313, "s": 36064, "text": "“*=”(Multiply Assignment) : This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example :" }, { "code": null, "e": 36357, "s": 36313, "text": "($a *= $b) can be written as ($a = $a * $b)" }, { "code": null, "e": 36415, "s": 36357, "text": "If initially value stored in a is 5. Then ($a *= 6) = 30." }, { "code": null, "e": 36661, "s": 36415, "text": "“/=”(Division Assignment) : This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example :" }, { "code": null, "e": 36705, "s": 36661, "text": "($a /= $b) can be written as ($a = $a / $b)" }, { "code": null, "e": 36762, "s": 36705, "text": "If initially value stored in a is 6. Then ($a /= 2) = 3." }, { "code": null, "e": 37008, "s": 36762, "text": "“%=”(Modulus Assignment) : This operator is combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example : " }, { "code": null, "e": 37052, "s": 37008, "text": "($a %= $b) can be written as ($a = $a % $b)" }, { "code": null, "e": 37109, "s": 37052, "text": "If initially value stored in a is 6. Then ($a %= 2) = 0." }, { "code": null, "e": 37358, "s": 37109, "text": "“**=”(Exponent Assignment) : This operator is combination of ‘**’ and ‘=’ operators. This operator first exponent the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example :" }, { "code": null, "e": 37404, "s": 37358, "text": "($a **= $b) can be written as ($a = $a ** $b)" }, { "code": null, "e": 37464, "s": 37404, "text": "If initially, value stored in a is 6. Then ($a **= 2) = 36." }, { "code": null, "e": 37525, "s": 37464, "text": "Program: To demonstrate the working of Assignment Operators " }, { "code": null, "e": 37530, "s": 37525, "text": "Perl" }, { "code": "# Perl program to demonstrate the working# of Assignment Operators#!/usr/local/bin/perl # taking two variables & using# simple assignments operation$a = 8;$b = 5; # using Assignment Operatorsprint \"Addition Assignment Operator: \", $a += $b, \"\\n\"; $a = 8;$b = 4;print \"Subtraction Assignment Operator: \", $a -= $b, \"\\n\" ; $a = 8;$b = 4;print \"Multiplication Assignment Operator: \", $a*=$b, \"\\n\"; $a = 8;$b = 4;print \"Division Assignment Operator: \",$a/=$b, \"\\n\"; $a = 8;$b = 5;print \"Modulo Assignment Operator: \", $a%=$b,\"\\n\"; $a = 8;$b = 4;print \"Exponent Assignment Operator: \", $a**=$b, \"\\n\"; ", "e": 38135, "s": 37530, "text": null }, { "code": null, "e": 38144, "s": 38135, "text": "Output: " }, { "code": null, "e": 38348, "s": 38144, "text": "Addition Assignment Operator: 13\nSubtraction Assignment Operator: 4\nMultiplication Assignment Operator: 32\nDivision Assignment Operator: 2\nModulo Assignment Operator: 3\nExponent Assignment Operator: 4096" }, { "code": null, "e": 38365, "s": 38348, "text": "Ternary Operator" }, { "code": null, "e": 38576, "s": 38365, "text": "It is a conditional operator which is a shorthand version of if-else statement. It has three operands and hence the name ternary. It will return one of two values depending on the value of a Boolean expression." }, { "code": null, "e": 38585, "s": 38576, "text": "Syntax: " }, { "code": null, "e": 38635, "s": 38585, "text": "condition ? first_expression : second_expression;" }, { "code": null, "e": 38650, "s": 38635, "text": "Explanation: " }, { "code": null, "e": 38861, "s": 38650, "text": "condition: It must be evaluated to true or false.\nIf the condition is true\nfirst_expression is evaluated and becomes the result.\nIf the condition is false,\nsecond_expression is evaluated and becomes the result." }, { "code": null, "e": 38872, "s": 38861, "text": "Example: " }, { "code": null, "e": 38877, "s": 38872, "text": "Perl" }, { "code": "# Perl program to demonstrate the working# of Ternary Operator $x = 5;$y = 10; # To find which value is greater# Using Ternary Operator$result = $x > $y ? $x : $y; # displaying the outputprint \"The Larger Number is: $result\" ", "e": 39108, "s": 38877, "text": null }, { "code": null, "e": 39117, "s": 39108, "text": "Output: " }, { "code": null, "e": 39142, "s": 39117, "text": "The Larger Number is: 10" }, { "code": null, "e": 39312, "s": 39142, "text": "Note: In the Ternary operator the condition can be any expression also which can make by using the different operators like relational operators, logical operators, etc." }, { "code": null, "e": 39323, "s": 39312, "text": "Example: " }, { "code": null, "e": 39328, "s": 39323, "text": "Perl" }, { "code": "# Perl program to demonstrate the working# of Ternary Operator by using expression# as the condition # here maximum value can be 100$MAX_VALUE = 100; # suppose user provide value$user_value = 444; # To find which whether user provided# value is satisfying the maximum value# or not by using Ternary Operator$result = $user_value <= $MAX_VALUE ? $user_value : $MAX_VALUE; # displaying the output# Here it will be MAX_VALUEprint \"$result\" ", "e": 39770, "s": 39328, "text": null }, { "code": null, "e": 39779, "s": 39770, "text": "Output: " }, { "code": null, "e": 39783, "s": 39779, "text": "100" }, { "code": null, "e": 39798, "s": 39785, "text": "Akanksha_Rai" }, { "code": null, "e": 39808, "s": 39798, "text": "Code_Mech" }, { "code": null, "e": 39824, "s": 39808, "text": "simranarora5sos" }, { "code": null, "e": 39837, "s": 39824, "text": "simmytarika5" }, { "code": null, "e": 39849, "s": 39837, "text": "perl-basics" }, { "code": null, "e": 39864, "s": 39849, "text": "perl-operators" }, { "code": null, "e": 39869, "s": 39864, "text": "Perl" }, { "code": null, "e": 39874, "s": 39869, "text": "Perl" }, { "code": null, "e": 39972, "s": 39874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39996, "s": 39972, "text": "Perl | split() Function" }, { "code": null, "e": 40019, "s": 39996, "text": "Perl | push() Function" }, { "code": null, "e": 40043, "s": 40019, "text": "Perl | chomp() Function" }, { "code": null, "e": 40066, "s": 40043, "text": "Perl | grep() Function" }, { "code": null, "e": 40091, "s": 40066, "text": "Perl | substr() function" }, { "code": null, "e": 40116, "s": 40091, "text": "Perl | exists() Function" }, { "code": null, "e": 40157, "s": 40116, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 40214, "s": 40157, "text": "Perl | Removing leading and trailing white spaces (trim)" }, { "code": null, "e": 40247, "s": 40214, "text": "Use of print() and say() in Perl" } ]
Perl | Slurp Module - GeeksforGeeks
17 Feb, 2022 The File::Slurp module is used to read contents of a file and store it into a string. It is a simple and efficient way of Reading/Writing/Modifying complete files. Just like its name, it allows you to read or write entire files with one simple call. By importing this module to your program, the user can implement some functions like read_file, read_text, write_file, etc. to read and write content to/from the file.Installation of File::Slurp Module: To use this module, there is a need to first add it to your Perl language package. This can be done by using the following commands in your Perl Terminal and installing the required module.Step 1: Open your terminal and run the following command: perl -MCPAN -e shell After entering into the cpan shell, follow the next step to install the File::Slurp module. Step 2: Run following command to install the module: install File::Slurp This will install the File::Slurp module. Step 3: Type and run ‘q’ command to exit from the cpan> prompt.read_file function in Slurp: File::Slurp’s read_file function reads entire contents of a file with the file name and returns it as a string. However, the use of File::Slurp is not encouraged as it has few encoding layer problems that may cause issues during compilation. File::Slurper aims to be an alternative to avoid the above-mentioned issues. Syntax: use File::Slurp; my $text = read_file($filename);Return: It returns a string. read_text function in Slurp: File::Slurper’s read_text function accepts an optional encoding argument (if any), and can automatically decode CRLF line endings if you request it (for Windows files). Syntax: use File::Slurper; my $content = read_text($filename);Return: It returns a string. Note: CRLF line endings are used to mark a line break in a text file (Windows line break types).write_file function in Slurp: File::Slurp’s write_file function is used to write to files all at once with the use of File::Slurp module. It writes to file with the help of a Scalar variable that contains the content of another file read by read_file function. Syntax: use File::Slurp; write_file($filename, $content);Returns: It doesn’t return any value, just writes the content to the file. Example1: Using scalar to store file content PERL # Perl code to illustrate the slurp functionuse File::Slurp; # read the whole file into a scalarmy $content = read_file('C:\Users\GeeksForGeeks\GFG_Slurp.txt'); # write out a whole file from a scalarwrite_file('C:\Users\GeeksForGeeks\Copyof_GFG_Slurp.txt', $content); Output : Explanation: In the above Perl code, initially, we used a slurp function to read a file named GFG_Slurp.txt containing some lines of text as an input into a scalar variable named $content and then wrote the contents of the file into another file Copyof_GFG_Slurp.txt as a single string.Example2: Using Array to store file content PERL # perl code to illustrate the slurp functionuse File::Slurp; # read the whole file into a scalarmy @lines = read_file('C:\Users\GeeksForGeeks\GFG_Slurp2.txt'); # write out a whole file from a scalarwrite_file('C:\Users\GeeksForGeeks\Copyof_GFG_Slurp2.txt', @lines); Output : Explanation: In the above Perl code, initially, we used a slurp function to read a file named GFG_Slurp2.txt containing an array of lines of text as an input into a array variable named @lines and then wrote the contents of the entire file into a file named Copyof_GFG_Slurp2.txt as a single string.Example3: Creating a function to use slurp method Perl # Perl code to illustrate the slurp functionuse strict;use warnings;use File::Slurp; # calling user defined functionget_a_string(); sub get_a_string{ # read entire file into a scalar my $gfg_str = read_file('C:\Users\GeeksForGeeks\GFG_User_Slurp.txt'); # write entire file from a scalar write_file('C:\Users\GeeksForGeeks\Copyof_GFG_User_Slurp.txt', $gfg_str);} Output : Explanation:In the above Perl code, strict and warnings allow the user to enter code more liberally and catch errors sooner such as typos in variable names, etc. We called a user-defined function named get_a_string which in turn executes the slurp function i.e.., it reads a file containing some lines of text as an input into a variable named gfg_str and then wrote the contents of the entire file into a file as a single string. sumitgumber28 Perl-File-Functions Perl-files Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays (push, pop, shift, unshift) Perl | Arrays Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | length() Function Perl | join() Function Perl | Basic Syntax of a Perl Program Perl | Boolean Values Perl | sleep() Function Perl | Subroutines or Functions
[ { "code": null, "e": 25277, "s": 25249, "text": "\n17 Feb, 2022" }, { "code": null, "e": 25979, "s": 25277, "text": "The File::Slurp module is used to read contents of a file and store it into a string. It is a simple and efficient way of Reading/Writing/Modifying complete files. Just like its name, it allows you to read or write entire files with one simple call. By importing this module to your program, the user can implement some functions like read_file, read_text, write_file, etc. to read and write content to/from the file.Installation of File::Slurp Module: To use this module, there is a need to first add it to your Perl language package. This can be done by using the following commands in your Perl Terminal and installing the required module.Step 1: Open your terminal and run the following command: " }, { "code": null, "e": 26000, "s": 25979, "text": "perl -MCPAN -e shell" }, { "code": null, "e": 26149, "s": 26002, "text": "After entering into the cpan shell, follow the next step to install the File::Slurp module. Step 2: Run following command to install the module: " }, { "code": null, "e": 26169, "s": 26149, "text": "install File::Slurp" }, { "code": null, "e": 26626, "s": 26171, "text": "This will install the File::Slurp module. Step 3: Type and run ‘q’ command to exit from the cpan> prompt.read_file function in Slurp: File::Slurp’s read_file function reads entire contents of a file with the file name and returns it as a string. However, the use of File::Slurp is not encouraged as it has few encoding layer problems that may cause issues during compilation. File::Slurper aims to be an alternative to avoid the above-mentioned issues. " }, { "code": null, "e": 26712, "s": 26626, "text": "Syntax: use File::Slurp; my $text = read_file($filename);Return: It returns a string." }, { "code": null, "e": 26911, "s": 26712, "text": "read_text function in Slurp: File::Slurper’s read_text function accepts an optional encoding argument (if any), and can automatically decode CRLF line endings if you request it (for Windows files). " }, { "code": null, "e": 27002, "s": 26911, "text": "Syntax: use File::Slurper; my $content = read_text($filename);Return: It returns a string." }, { "code": null, "e": 27360, "s": 27002, "text": "Note: CRLF line endings are used to mark a line break in a text file (Windows line break types).write_file function in Slurp: File::Slurp’s write_file function is used to write to files all at once with the use of File::Slurp module. It writes to file with the help of a Scalar variable that contains the content of another file read by read_file function. " }, { "code": null, "e": 27492, "s": 27360, "text": "Syntax: use File::Slurp; write_file($filename, $content);Returns: It doesn’t return any value, just writes the content to the file." }, { "code": null, "e": 27538, "s": 27492, "text": "Example1: Using scalar to store file content " }, { "code": null, "e": 27543, "s": 27538, "text": "PERL" }, { "code": "# Perl code to illustrate the slurp functionuse File::Slurp; # read the whole file into a scalarmy $content = read_file('C:\\Users\\GeeksForGeeks\\GFG_Slurp.txt'); # write out a whole file from a scalarwrite_file('C:\\Users\\GeeksForGeeks\\Copyof_GFG_Slurp.txt', $content);", "e": 27811, "s": 27543, "text": null }, { "code": null, "e": 27822, "s": 27811, "text": "Output : " }, { "code": null, "e": 28157, "s": 27826, "text": "Explanation: In the above Perl code, initially, we used a slurp function to read a file named GFG_Slurp.txt containing some lines of text as an input into a scalar variable named $content and then wrote the contents of the file into another file Copyof_GFG_Slurp.txt as a single string.Example2: Using Array to store file content " }, { "code": null, "e": 28162, "s": 28157, "text": "PERL" }, { "code": "# perl code to illustrate the slurp functionuse File::Slurp; # read the whole file into a scalarmy @lines = read_file('C:\\Users\\GeeksForGeeks\\GFG_Slurp2.txt'); # write out a whole file from a scalarwrite_file('C:\\Users\\GeeksForGeeks\\Copyof_GFG_Slurp2.txt', @lines);", "e": 28428, "s": 28162, "text": null }, { "code": null, "e": 28439, "s": 28428, "text": "Output : " }, { "code": null, "e": 28793, "s": 28443, "text": "Explanation: In the above Perl code, initially, we used a slurp function to read a file named GFG_Slurp2.txt containing an array of lines of text as an input into a array variable named @lines and then wrote the contents of the entire file into a file named Copyof_GFG_Slurp2.txt as a single string.Example3: Creating a function to use slurp method " }, { "code": null, "e": 28798, "s": 28793, "text": "Perl" }, { "code": "# Perl code to illustrate the slurp functionuse strict;use warnings;use File::Slurp; # calling user defined functionget_a_string(); sub get_a_string{ # read entire file into a scalar my $gfg_str = read_file('C:\\Users\\GeeksForGeeks\\GFG_User_Slurp.txt'); # write entire file from a scalar write_file('C:\\Users\\GeeksForGeeks\\Copyof_GFG_User_Slurp.txt', $gfg_str);}", "e": 29166, "s": 28798, "text": null }, { "code": null, "e": 29177, "s": 29166, "text": "Output : " }, { "code": null, "e": 29613, "s": 29181, "text": "Explanation:In the above Perl code, strict and warnings allow the user to enter code more liberally and catch errors sooner such as typos in variable names, etc. We called a user-defined function named get_a_string which in turn executes the slurp function i.e.., it reads a file containing some lines of text as an input into a variable named gfg_str and then wrote the contents of the entire file into a file as a single string. " }, { "code": null, "e": 29627, "s": 29613, "text": "sumitgumber28" }, { "code": null, "e": 29647, "s": 29627, "text": "Perl-File-Functions" }, { "code": null, "e": 29658, "s": 29647, "text": "Perl-files" }, { "code": null, "e": 29665, "s": 29658, "text": "Picked" }, { "code": null, "e": 29670, "s": 29665, "text": "Perl" }, { "code": null, "e": 29675, "s": 29670, "text": "Perl" }, { "code": null, "e": 29773, "s": 29675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29815, "s": 29773, "text": "Perl | Arrays (push, pop, shift, unshift)" }, { "code": null, "e": 29829, "s": 29815, "text": "Perl | Arrays" }, { "code": null, "e": 29870, "s": 29829, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29903, "s": 29870, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 29928, "s": 29903, "text": "Perl | length() Function" }, { "code": null, "e": 29951, "s": 29928, "text": "Perl | join() Function" }, { "code": null, "e": 29989, "s": 29951, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 30011, "s": 29989, "text": "Perl | Boolean Values" }, { "code": null, "e": 30035, "s": 30011, "text": "Perl | sleep() Function" } ]
ArrayList size() method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The size() method of java.util.ArrayList class is used to get the number of elements in this list. Syntax: public int size() Returns Value: This method returns the number of elements in this list. Below are the examples to illustrate the size() method. Example 1: // Java program to demonstrate// size() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println("Before operation: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println("Size of list = " + size); } catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown: " + e); } }} Before operation: [1, 2, 3, 4, 5] Size of list = 5 Example 2: // Java program to demonstrate// size() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add("A"); arrlist.add("B"); arrlist.add("C"); // print arrlist System.out.println("Before operation: " + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println("Size of list = " + size); } catch (IndexOutOfBoundsException e) { System.out.println("Exception thrown: " + e); } }} Before operation: [A, B, C] Size of list = 3 Java - util package Java-ArrayList Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26248, "s": 26220, "text": "\n26 Nov, 2018" }, { "code": null, "e": 26347, "s": 26248, "text": "The size() method of java.util.ArrayList class is used to get the number of elements in this list." }, { "code": null, "e": 26355, "s": 26347, "text": "Syntax:" }, { "code": null, "e": 26373, "s": 26355, "text": "public int size()" }, { "code": null, "e": 26445, "s": 26373, "text": "Returns Value: This method returns the number of elements in this list." }, { "code": null, "e": 26501, "s": 26445, "text": "Below are the examples to illustrate the size() method." }, { "code": null, "e": 26512, "s": 26501, "text": "Example 1:" }, { "code": "// Java program to demonstrate// size() method// for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<Integer> arrlist = new ArrayList<Integer>(); // Populating arrlist1 arrlist.add(1); arrlist.add(2); arrlist.add(3); arrlist.add(4); arrlist.add(5); // print arrlist System.out.println(\"Before operation: \" + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println(\"Size of list = \" + size); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 27541, "s": 26512, "text": null }, { "code": null, "e": 27593, "s": 27541, "text": "Before operation: [1, 2, 3, 4, 5]\nSize of list = 5\n" }, { "code": null, "e": 27604, "s": 27593, "text": "Example 2:" }, { "code": "// Java program to demonstrate// size() method// for String value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of ArrayList<Integer> ArrayList<String> arrlist = new ArrayList<String>(); // Populating arrlist1 arrlist.add(\"A\"); arrlist.add(\"B\"); arrlist.add(\"C\"); // print arrlist System.out.println(\"Before operation: \" + arrlist); // getting total size of arrlist // using size() method int size = arrlist.size(); // print the size of arrlist System.out.println(\"Size of list = \" + size); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 28582, "s": 27604, "text": null }, { "code": null, "e": 28628, "s": 28582, "text": "Before operation: [A, B, C]\nSize of list = 3\n" }, { "code": null, "e": 28648, "s": 28628, "text": "Java - util package" }, { "code": null, "e": 28663, "s": 28648, "text": "Java-ArrayList" }, { "code": null, "e": 28680, "s": 28663, "text": "Java-Collections" }, { "code": null, "e": 28695, "s": 28680, "text": "Java-Functions" }, { "code": null, "e": 28700, "s": 28695, "text": "Java" }, { "code": null, "e": 28705, "s": 28700, "text": "Java" }, { "code": null, "e": 28722, "s": 28705, "text": "Java-Collections" }, { "code": null, "e": 28820, "s": 28722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28871, "s": 28820, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28901, "s": 28871, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28916, "s": 28901, "text": "Stream In Java" }, { "code": null, "e": 28935, "s": 28916, "text": "Interfaces in Java" }, { "code": null, "e": 28966, "s": 28935, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28984, "s": 28966, "text": "ArrayList in Java" }, { "code": null, "e": 29016, "s": 28984, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29036, "s": 29016, "text": "Stack Class in Java" }, { "code": null, "e": 29060, "s": 29036, "text": "Singleton Class in Java" } ]
reflect.Interface() Function in Golang with Examples - GeeksforGeeks
03 May, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Interface() Function in Golang is used to get the v’s current value as an interface{}. To access this function, one needs to imports the reflect package in the program. Syntax: func (v Value) Interface() (i interface{}) Parameters: This function accept only one parameter. i : This parameter is the interface{} type Return Value: This function returns v’s current value as an interface{}. Below examples illustrate the use of the above method in Golang: Example 1: // Golang program to illustrate// reflect.Interface() Function package main import ( "fmt" "reflect") // Main function func main() { t := reflect.TypeOf(5) //use of Interface method arr := reflect.ArrayOf(4, t) inst := reflect.New(arr).Interface().(*[4]int) for i := 1; i <= 4; i++ { inst[i-1] = i*i } fmt.Println(inst)} Output: &[1 4 9 16] Example 2: // Golang program to illustrate// reflect.Interface() Function package main import ( "fmt" "reflect") // Main functionfunc main() { var str []string var v reflect.Value = reflect.ValueOf(&str) v = v.Elem() v = reflect.Append(v, reflect.ValueOf("a")) v = reflect.Append(v, reflect.ValueOf("b")) v = reflect.Append(v, reflect.ValueOf("c"), reflect.ValueOf("j, k, l")) fmt.Println("Our value is a type of :", v.Kind()) vSlice := v.Slice(0, v.Len()) vSliceElems := vSlice.Interface() fmt.Println("With the elements of : ", vSliceElems) } Output: Our value is a type of : slice With the elements of : [a b c j, k, l] Golang-reflect Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go How to Split a String in Golang? Slices in Golang Golang Maps Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang How to Trim a String in Golang? How to compare times in Golang?
[ { "code": null, "e": 25837, "s": 25809, "text": "\n03 May, 2020" }, { "code": null, "e": 26193, "s": 25837, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Interface() Function in Golang is used to get the v’s current value as an interface{}. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 26201, "s": 26193, "text": "Syntax:" }, { "code": null, "e": 26245, "s": 26201, "text": "func (v Value) Interface() (i interface{})\n" }, { "code": null, "e": 26298, "s": 26245, "text": "Parameters: This function accept only one parameter." }, { "code": null, "e": 26341, "s": 26298, "text": "i : This parameter is the interface{} type" }, { "code": null, "e": 26414, "s": 26341, "text": "Return Value: This function returns v’s current value as an interface{}." }, { "code": null, "e": 26479, "s": 26414, "text": "Below examples illustrate the use of the above method in Golang:" }, { "code": null, "e": 26490, "s": 26479, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.Interface() Function package main import ( \"fmt\" \"reflect\") // Main function func main() { t := reflect.TypeOf(5) //use of Interface method arr := reflect.ArrayOf(4, t) inst := reflect.New(arr).Interface().(*[4]int) for i := 1; i <= 4; i++ { inst[i-1] = i*i } fmt.Println(inst)}", "e": 26865, "s": 26490, "text": null }, { "code": null, "e": 26873, "s": 26865, "text": "Output:" }, { "code": null, "e": 26886, "s": 26873, "text": "&[1 4 9 16]\n" }, { "code": null, "e": 26897, "s": 26886, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.Interface() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { var str []string var v reflect.Value = reflect.ValueOf(&str) v = v.Elem() v = reflect.Append(v, reflect.ValueOf(\"a\")) v = reflect.Append(v, reflect.ValueOf(\"b\")) v = reflect.Append(v, reflect.ValueOf(\"c\"), reflect.ValueOf(\"j, k, l\")) fmt.Println(\"Our value is a type of :\", v.Kind()) vSlice := v.Slice(0, v.Len()) vSliceElems := vSlice.Interface() fmt.Println(\"With the elements of : \", vSliceElems) }", "e": 27496, "s": 26897, "text": null }, { "code": null, "e": 27504, "s": 27496, "text": "Output:" }, { "code": null, "e": 27576, "s": 27504, "text": "Our value is a type of : slice\nWith the elements of : [a b c j, k, l]\n" }, { "code": null, "e": 27591, "s": 27576, "text": "Golang-reflect" }, { "code": null, "e": 27603, "s": 27591, "text": "Go Language" }, { "code": null, "e": 27701, "s": 27603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27747, "s": 27701, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27760, "s": 27747, "text": "Arrays in Go" }, { "code": null, "e": 27793, "s": 27760, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27810, "s": 27793, "text": "Slices in Golang" }, { "code": null, "e": 27822, "s": 27810, "text": "Golang Maps" }, { "code": null, "e": 27844, "s": 27822, "text": "Inheritance in GoLang" }, { "code": null, "e": 27898, "s": 27844, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 27919, "s": 27898, "text": "Interfaces in Golang" }, { "code": null, "e": 27951, "s": 27919, "text": "How to Trim a String in Golang?" } ]
Class getConstructor() method in Java with Examples - GeeksforGeeks
16 Dec, 2019 The getConstructor() method of java.lang.Class class is used to get the specified constructor of this class with the specified parameter type, which is the constructor that is public and its members. The method returns the specified constructor of this class in the form of Constructor object. Syntax: public Constructor<T> getConstructor(Class[] parameterType) throws NoSuchMethodException, SecurityException Parameter: This constructor accepts a parameters parameterType which is the array of parameter type for the specified constructor. Return Value: This method returns the specified constructor of this class in the form of Constructor objects. Exception This method throws: NoSuchMethodException if a constructor with the specified name is not found. NullPointerException if name is null SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getConstructor() method.Example 1:// Java program to demonstrate// getConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getConstructor() method System.out.println( "Constructor of myClass: " + myClass.getConstructor(parameterType)); }}Output:Class represented by myClass: class Test Constructor of myClass: public Test() Example 2:// Java program to demonstrate// getConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; try { // Get the constructor of myClass // using getConstructor() method System.out.println( "Constructor of myClass: " + myClass.getConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main java.lang.NoSuchMethodException: Main.<init>() Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getConstructor-java.lang.Class...-My Personal Notes arrow_drop_upSave Below programs demonstrate the getConstructor() method. Example 1: // Java program to demonstrate// getConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getConstructor() method System.out.println( "Constructor of myClass: " + myClass.getConstructor(parameterType)); }} Class represented by myClass: class Test Constructor of myClass: public Test() Example 2: // Java program to demonstrate// getConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); Class[] parameterType = null; try { // Get the constructor of myClass // using getConstructor() method System.out.println( "Constructor of myClass: " + myClass.getConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }} Class represented by myClass: class Main java.lang.NoSuchMethodException: Main.<init>() Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getConstructor-java.lang.Class...- Java-Functions Java-lang package Java.lang.Class Java 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 Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n16 Dec, 2019" }, { "code": null, "e": 25519, "s": 25225, "text": "The getConstructor() method of java.lang.Class class is used to get the specified constructor of this class with the specified parameter type, which is the constructor that is public and its members. The method returns the specified constructor of this class in the form of Constructor object." }, { "code": null, "e": 25527, "s": 25519, "text": "Syntax:" }, { "code": null, "e": 25664, "s": 25527, "text": "public Constructor<T>\n getConstructor(Class[] parameterType)\n throws NoSuchMethodException,\n SecurityException\n" }, { "code": null, "e": 25795, "s": 25664, "text": "Parameter: This constructor accepts a parameters parameterType which is the array of parameter type for the specified constructor." }, { "code": null, "e": 25905, "s": 25795, "text": "Return Value: This method returns the specified constructor of this class in the form of Constructor objects." }, { "code": null, "e": 25935, "s": 25905, "text": "Exception This method throws:" }, { "code": null, "e": 26012, "s": 25935, "text": "NoSuchMethodException if a constructor with the specified name is not found." }, { "code": null, "e": 26049, "s": 26012, "text": "NullPointerException if name is null" }, { "code": null, "e": 28019, "s": 26049, "text": "SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getConstructor() method.Example 1:// Java program to demonstrate// getConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getConstructor(parameterType)); }}Output:Class represented by myClass: class Test\nConstructor of myClass: public Test()\nExample 2:// Java program to demonstrate// getConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; try { // Get the constructor of myClass // using getConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}Output:Class represented by myClass: class Main\njava.lang.NoSuchMethodException: Main.<init>()\nReference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getConstructor-java.lang.Class...-My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28075, "s": 28019, "text": "Below programs demonstrate the getConstructor() method." }, { "code": null, "e": 28086, "s": 28075, "text": "Example 1:" }, { "code": "// Java program to demonstrate// getConstructor() method import java.util.*; public class Test { public Test() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; // Get the constructor of myClass // using getConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getConstructor(parameterType)); }}", "e": 28770, "s": 28086, "text": null }, { "code": null, "e": 28850, "s": 28770, "text": "Class represented by myClass: class Test\nConstructor of myClass: public Test()\n" }, { "code": null, "e": 28861, "s": 28850, "text": "Example 2:" }, { "code": "// Java program to demonstrate// getConstructor() constructor import java.util.*; class Main { private Main() {} public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); Class[] parameterType = null; try { // Get the constructor of myClass // using getConstructor() method System.out.println( \"Constructor of myClass: \" + myClass.getConstructor(parameterType)); } catch (Exception e) { System.out.println(e); } }}", "e": 29658, "s": 28861, "text": null }, { "code": null, "e": 29747, "s": 29658, "text": "Class represented by myClass: class Main\njava.lang.NoSuchMethodException: Main.<init>()\n" }, { "code": null, "e": 29856, "s": 29747, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getConstructor-java.lang.Class...-" }, { "code": null, "e": 29871, "s": 29856, "text": "Java-Functions" }, { "code": null, "e": 29889, "s": 29871, "text": "Java-lang package" }, { "code": null, "e": 29905, "s": 29889, "text": "Java.lang.Class" }, { "code": null, "e": 29910, "s": 29905, "text": "Java" }, { "code": null, "e": 29915, "s": 29910, "text": "Java" }, { "code": null, "e": 30013, "s": 29915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30028, "s": 30013, "text": "Stream In Java" }, { "code": null, "e": 30049, "s": 30028, "text": "Constructors in Java" }, { "code": null, "e": 30068, "s": 30049, "text": "Exceptions in Java" }, { "code": null, "e": 30098, "s": 30068, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30144, "s": 30098, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30161, "s": 30144, "text": "Generics in Java" }, { "code": null, "e": 30182, "s": 30161, "text": "Introduction to Java" }, { "code": null, "e": 30225, "s": 30182, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30261, "s": 30225, "text": "Internal Working of HashMap in Java" } ]
How To Calculate Variance in Excel? - GeeksforGeeks
09 May, 2021 In this article, we will learn about the calculation of the variance(var) in Excel. First, let’s learn about Variance. In real-life scenarios, we have populations like marks of students in a particular subject, salaries of multiple employees in a company. Let us consider, in a company named ABC, we have 5 employees. Now, it will tell us the expectation of standard deviation. In other words, the factor of difference in salaries. The formula for std is – \sigma^{2} = \sum_1^n (x_{i} - \mu )^{2} / N It will be shown as Where x represents the value, and μ is the mean of the sample. Mean = 30 N = 5 Var = 200 Now, Let’s learn how to use it in Excel – In Excel we have formulas for everything and as you might have guessed for var also. We can have this list of formulas using ‘=’ symbol shown below Let’s talk about them briefly, 1. VAR.P – It calculates the var assuming that the entire population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown above. 2. VAR.S – It calculates the var assuming that the sample of the population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown below \sigma^{2} = \sum_1^n (x_{i} - \mu )^{2} / (N -1) 3. VARA – It includes text and logical symbols whereas the above 2 functions don’t include text and logical symbols. It is used for a sample of the population. Uses “n-1” formula. 4. VARPA – It includes text and logical symbols. It is used for the whole population. Uses “n” formula. Let’s see the difference here, Here, the discrepancy occurs because VARPA and VARA read TRUE as 1 and VAR.P and VAR.S ignore it. The formula goes like this – 1. =STDEV.P(A38:A43) [Formula used in A37 cell] 2. =STDEV.S(B38:B43) [Formula used in B37 cell] 3. =STDEVPA(C38:B43) [Formula used in C37 cell] 4. =STDEVA(D38:B43) [Formula used in D37 cell] Note – VAR and VARP are for Excel 2007 or earlier. DVAR and DVARP are used for fetching data from Database. Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel How to Extract the Last Word From a Cell in Excel? Introduction to Excel Spreadsheet How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n09 May, 2021" }, { "code": null, "e": 26373, "s": 26289, "text": "In this article, we will learn about the calculation of the variance(var) in Excel." }, { "code": null, "e": 26607, "s": 26373, "text": "First, let’s learn about Variance. In real-life scenarios, we have populations like marks of students in a particular subject, salaries of multiple employees in a company. Let us consider, in a company named ABC, we have 5 employees." }, { "code": null, "e": 26721, "s": 26607, "text": "Now, it will tell us the expectation of standard deviation. In other words, the factor of difference in salaries." }, { "code": null, "e": 26746, "s": 26721, "text": "The formula for std is –" }, { "code": null, "e": 26797, "s": 26746, "text": "\\sigma^{2} = \\sum_1^n (x_{i} - \\mu )^{2} / N" }, { "code": null, "e": 26817, "s": 26797, "text": "It will be shown as" }, { "code": null, "e": 26880, "s": 26817, "text": "Where x represents the value, and μ is the mean of the sample." }, { "code": null, "e": 26890, "s": 26880, "text": "Mean = 30" }, { "code": null, "e": 26896, "s": 26890, "text": "N = 5" }, { "code": null, "e": 26906, "s": 26896, "text": "Var = 200" }, { "code": null, "e": 26948, "s": 26906, "text": "Now, Let’s learn how to use it in Excel –" }, { "code": null, "e": 27033, "s": 26948, "text": "In Excel we have formulas for everything and as you might have guessed for var also." }, { "code": null, "e": 27096, "s": 27033, "text": "We can have this list of formulas using ‘=’ symbol shown below" }, { "code": null, "e": 27127, "s": 27096, "text": "Let’s talk about them briefly," }, { "code": null, "e": 27317, "s": 27127, "text": "1. VAR.P – It calculates the var assuming that the entire population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown above." }, { "code": null, "e": 27513, "s": 27317, "text": "2. VAR.S – It calculates the var assuming that the sample of the population is its argument. It returns an approximate value and is used with a large population. Uses the same formula shown below" }, { "code": null, "e": 27569, "s": 27513, "text": "\\sigma^{2} = \\sum_1^n (x_{i} - \\mu )^{2} / (N -1)" }, { "code": null, "e": 27749, "s": 27569, "text": "3. VARA – It includes text and logical symbols whereas the above 2 functions don’t include text and logical symbols. It is used for a sample of the population. Uses “n-1” formula." }, { "code": null, "e": 27853, "s": 27749, "text": "4. VARPA – It includes text and logical symbols. It is used for the whole population. Uses “n” formula." }, { "code": null, "e": 27884, "s": 27853, "text": "Let’s see the difference here," }, { "code": null, "e": 27982, "s": 27884, "text": "Here, the discrepancy occurs because VARPA and VARA read TRUE as 1 and VAR.P and VAR.S ignore it." }, { "code": null, "e": 28011, "s": 27982, "text": "The formula goes like this –" }, { "code": null, "e": 28231, "s": 28011, "text": "1. =STDEV.P(A38:A43) [Formula used in A37 cell]\n2. =STDEV.S(B38:B43) [Formula used in B37 cell]\n3. =STDEVPA(C38:B43) [Formula used in C37 cell]\n4. =STDEVA(D38:B43) [Formula used in D37 cell]" }, { "code": null, "e": 28339, "s": 28231, "text": "Note – VAR and VARP are for Excel 2007 or earlier. DVAR and DVARP are used for fetching data from Database." }, { "code": null, "e": 28346, "s": 28339, "text": "Picked" }, { "code": null, "e": 28352, "s": 28346, "text": "Excel" }, { "code": null, "e": 28450, "s": 28352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28478, "s": 28450, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 28533, "s": 28478, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 28574, "s": 28533, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 28624, "s": 28574, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 28640, "s": 28624, "text": "Macros in Excel" }, { "code": null, "e": 28691, "s": 28640, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 28725, "s": 28691, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 28783, "s": 28725, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 28839, "s": 28783, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
GATE | GATE-CS-2003 | Question 81 - GeeksforGeeks
28 Jul, 2021 Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below. Process P: while (1) { W: print '0'; print '0'; X: } Process Q: while (1) { Y: print '1'; print '1'; Z: } Synchronization statements can be inserted only at points W, X, Y and Z Which of the following will ensure that the output string never contains a substring of the form 01^n0 or 10^n1 where n is odd?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(C) P(S) at W, V(S) at X, P(S) at Y, V(S) at Z, S initially 1(D) V(S) at W, V(T) at X, P(S) at Y, P(T) at Z, S and T initially 1Answer: (C)Explanation: P(S) means wait on semaphore ’S’ and V(S) means signal on semaphore ‘S’. The definition of these functions are : Wait(S) { while (i <= 0) ; S-- ; } Signal(S) { S++ ; } Initially S = 1 and T = 0 to support mutual exclusion in process ‘P’ and ‘Q’.Since, S = 1 , process ‘P’ will be executed and function Wait(S) will decrement the value of ‘S’. So, S = 0 now.Simultaneously, in process ‘Q’ , T = 0 . Therefore, in process ‘Q’ control will be stuck in while loop till the time process ‘P’ prints ‘00’ and increments the value of ‘T’ by calling function V(T).While the control is in process ‘Q’, S = 0 and process ‘P’ will be stuck in while loop. Process ‘P’ will not execute till the time process ‘Q’ prints ‘11’ and makes S = 1 by calling function V(S). Thus, process ‘P’ and ‘Q’ will keep on repeating to give the output ‘00110011 ...... ‘ . Watch GeeksforGeeks Video Explanation : YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE Previous Year Questions based on Semaphore with Viomesh Singh | GeeksforGeeks GATE GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:50 / 1:00:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=MRza1t01xgE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please comment below if you find anything wrong in the above post.Quiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25863, "s": 25835, "text": "\n28 Jul, 2021" }, { "code": null, "e": 26011, "s": 25863, "text": "Suppose we want to synchronize two concurrent processes P and Q using binary semaphores S and T. The code for the processes P and Q is shown below." }, { "code": null, "e": 26131, "s": 26011, "text": "Process P:\nwhile (1) {\nW:\n print '0';\n print '0';\nX:\n}\n\t\nProcess Q:\nwhile (1) {\nY:\n print '1';\n print '1';\nZ:\n}" }, { "code": null, "e": 26203, "s": 26131, "text": "Synchronization statements can be inserted only at points W, X, Y and Z" }, { "code": null, "e": 26729, "s": 26203, "text": "Which of the following will ensure that the output string never contains a substring of the form 01^n0 or 10^n1 where n is odd?(A) P(S) at W, V(S) at X, P(T) at Y, V(T) at Z, S and T initially 1(B) P(S) at W, V(T) at X, P(T) at Y, V(S) at Z, S and T initially 1(C) P(S) at W, V(S) at X, P(S) at Y, V(S) at Z, S initially 1(D) V(S) at W, V(T) at X, P(S) at Y, P(T) at Z, S and T initially 1Answer: (C)Explanation: P(S) means wait on semaphore ’S’ and V(S) means signal on semaphore ‘S’. The definition of these functions are :" }, { "code": null, "e": 26801, "s": 26731, "text": "Wait(S) {\n while (i <= 0) ;\n S-- ; \n}\n\n\nSignal(S) {\n S++ ; \n}" }, { "code": null, "e": 27387, "s": 26803, "text": "Initially S = 1 and T = 0 to support mutual exclusion in process ‘P’ and ‘Q’.Since, S = 1 , process ‘P’ will be executed and function Wait(S) will decrement the value of ‘S’. So, S = 0 now.Simultaneously, in process ‘Q’ , T = 0 . Therefore, in process ‘Q’ control will be stuck in while loop till the time process ‘P’ prints ‘00’ and increments the value of ‘T’ by calling function V(T).While the control is in process ‘Q’, S = 0 and process ‘P’ will be stuck in while loop. Process ‘P’ will not execute till the time process ‘Q’ prints ‘11’ and makes S = 1 by calling function V(S)." }, { "code": null, "e": 27478, "s": 27389, "text": "Thus, process ‘P’ and ‘Q’ will keep on repeating to give the output ‘00110011 ...... ‘ ." }, { "code": null, "e": 27518, "s": 27478, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 28423, "s": 27518, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE Previous Year Questions based on Semaphore with Viomesh Singh | GeeksforGeeks GATE GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:50 / 1:00:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=MRza1t01xgE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 28512, "s": 28423, "text": " Please comment below if you find anything wrong in the above post.Quiz of this Question" }, { "code": null, "e": 28525, "s": 28512, "text": "GATE-CS-2003" }, { "code": null, "e": 28543, "s": 28525, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 28548, "s": 28543, "text": "GATE" }, { "code": null, "e": 28646, "s": 28548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28680, "s": 28646, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28714, "s": 28680, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28748, "s": 28714, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28781, "s": 28748, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28817, "s": 28781, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28853, "s": 28817, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28887, "s": 28853, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28921, "s": 28887, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28955, "s": 28921, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Remove first element from ArrayList in Java - GeeksforGeeks
26 Jan, 2020 Given an ArrayList collection in Java, the task is to remove the first element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 1, 2] Output: [20, 30, 1, 2] After removing the first element 10, the ArrayList is: [20, 30, 1, 2] Input: ArrayList[] = [1, 1, 2, 2, 3] Output: [1, 2, 2, 3] After removing the first element 1, the ArrayList is: [1, 2, 2, 3] We can use the remove() method of ArrayList container in Java to remove the first element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the first element’s index to the remove() method to delete the first element. remove(Object obj) : Accept object to be removed. If the ArrayList does not contain duplicates, we can simply pass the first element value as an object to be deleted to the remove() method, and it will delete that value.Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method. Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method. Below is the implementation to delete the first element using the two approaches: Program 1: Using remove(int index). Index of elements in an ArrayList starts from zero. Therefore, index of first element in an ArrayList is 0.// Java program to delete the first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // First element's index is always 0 int index = 0; // Delete first element by passing index al.remove(index); System.out.println("Modified ArrayList : " + al); }}Output:Modified ArrayList : [20, 30, 1, 2] // Java program to delete the first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // First element's index is always 0 int index = 0; // Delete first element by passing index al.remove(index); System.out.println("Modified ArrayList : " + al); }} Modified ArrayList : [20, 30, 1, 2] Program 2: Using remove(Object obj).// Java program to delete first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the first // elements value to delete it // Note: values are integer object al.remove(new Integer(10)); System.out.println("Modified ArrayList : " + al); }}Output:Modified ArrayList : [20, 30, 1, 2] // Java program to delete first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the first // elements value to delete it // Note: values are integer object al.remove(new Integer(10)); System.out.println("Modified ArrayList : " + al); }} Modified ArrayList : [20, 30, 1, 2] Java-ArrayList Java Java Programs 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": "\n26 Jan, 2020" }, { "code": null, "e": 25324, "s": 25225, "text": "Given an ArrayList collection in Java, the task is to remove the first element from the ArrayList." }, { "code": null, "e": 25333, "s": 25324, "text": "Example:" }, { "code": null, "e": 25593, "s": 25333, "text": "Input: ArrayList[] = [10, 20, 30, 1, 2]\nOutput: [20, 30, 1, 2]\nAfter removing the first element 10, the ArrayList is:\n[20, 30, 1, 2]\n\nInput: ArrayList[] = [1, 1, 2, 2, 3]\nOutput: [1, 2, 2, 3]\nAfter removing the first element 1, the ArrayList is:\n[1, 2, 2, 3]\n" }, { "code": null, "e": 25684, "s": 25593, "text": "We can use the remove() method of ArrayList container in Java to remove the first element." }, { "code": null, "e": 25735, "s": 25684, "text": "ArrayList provides two overloaded remove() method:" }, { "code": null, "e": 25887, "s": 25735, "text": "remove(int index) : Accept index of the object to be removed. We can pass the first element’s index to the remove() method to delete the first element." }, { "code": null, "e": 26251, "s": 25887, "text": "remove(Object obj) : Accept object to be removed. If the ArrayList does not contain duplicates, we can simply pass the first element value as an object to be deleted to the remove() method, and it will delete that value.Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method." }, { "code": null, "e": 26395, "s": 26251, "text": "Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method." }, { "code": null, "e": 26477, "s": 26395, "text": "Below is the implementation to delete the first element using the two approaches:" }, { "code": null, "e": 27182, "s": 26477, "text": "Program 1: Using remove(int index). Index of elements in an ArrayList starts from zero. Therefore, index of first element in an ArrayList is 0.// Java program to delete the first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // First element's index is always 0 int index = 0; // Delete first element by passing index al.remove(index); System.out.println(\"Modified ArrayList : \" + al); }}Output:Modified ArrayList : [20, 30, 1, 2]\n" }, { "code": "// Java program to delete the first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // First element's index is always 0 int index = 0; // Delete first element by passing index al.remove(index); System.out.println(\"Modified ArrayList : \" + al); }}", "e": 27701, "s": 27182, "text": null }, { "code": null, "e": 27738, "s": 27701, "text": "Modified ArrayList : [20, 30, 1, 2]\n" }, { "code": null, "e": 28362, "s": 27738, "text": "Program 2: Using remove(Object obj).// Java program to delete first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the first // elements value to delete it // Note: values are integer object al.remove(new Integer(10)); System.out.println(\"Modified ArrayList : \" + al); }}Output:Modified ArrayList : [20, 30, 1, 2]\n" }, { "code": "// Java program to delete first element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the first // elements value to delete it // Note: values are integer object al.remove(new Integer(10)); System.out.println(\"Modified ArrayList : \" + al); }}", "e": 28907, "s": 28362, "text": null }, { "code": null, "e": 28944, "s": 28907, "text": "Modified ArrayList : [20, 30, 1, 2]\n" }, { "code": null, "e": 28959, "s": 28944, "text": "Java-ArrayList" }, { "code": null, "e": 28964, "s": 28959, "text": "Java" }, { "code": null, "e": 28978, "s": 28964, "text": "Java Programs" }, { "code": null, "e": 28983, "s": 28978, "text": "Java" }, { "code": null, "e": 29081, "s": 28983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29096, "s": 29081, "text": "Stream In Java" }, { "code": null, "e": 29117, "s": 29096, "text": "Constructors in Java" }, { "code": null, "e": 29136, "s": 29117, "text": "Exceptions in Java" }, { "code": null, "e": 29166, "s": 29136, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29212, "s": 29166, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29238, "s": 29212, "text": "Java Programming Examples" }, { "code": null, "e": 29272, "s": 29238, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29319, "s": 29272, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29351, "s": 29319, "text": "How to Iterate HashMap in Java?" } ]
Java Program for Recursive Bubble Sort - GeeksforGeeks
28 Jun, 2021 Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i < n-1; i++) // Last i elements are already in place for (j = 0; j arr[j+1]) swap(arr[j], arr[j+1]); } Recursion Idea. Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray. Base Case: If array size is 1, return. Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray. Recur for all elements except last of current subarray. // Java program for recursive implementation// of Bubble sort import java.util.Arrays; public class GFG{ // A function to implement bubble sort static void bubbleSort(int arr[], int n) { // Base case if (n == 1) return; // One pass of bubble sort. After // this pass, the largest element // is moved (or bubbled) to end. for (int i=0; i<n-1; i++) if (arr[i] > arr[i+1]) { // swap arr[i], arr[i+1] int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } // Largest element is fixed, // recur for remaining array bubbleSort(arr, n-1); } // Driver Method public static void main(String[] args) { int arr[] = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr, arr.length); System.out.println("Sorted array : "); System.out.println(Arrays.toString(arr)); }} Please refer complete article on Recursive Bubble Sort for more details! BubbleSort Java Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Iterate through List in Java Program to print ASCII Value of a character Factory method design pattern in Java Java program to count the occurrence of each character in a string using Hashmap Bubble Sort Selection Sort std::sort() in C++ STL Time Complexities of all Sorting Algorithms
[ { "code": null, "e": 25217, "s": 25189, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25405, "s": 25217, "text": "Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm :" }, { "code": null, "e": 25602, "s": 25405, "text": "// Iterative Bubble Sort\nbubbleSort(arr[], n)\n{\n for (i = 0; i < n-1; i++) \n\n // Last i elements are already in place \n for (j = 0; j arr[j+1])\n swap(arr[j], arr[j+1]);\n} " }, { "code": null, "e": 25618, "s": 25602, "text": "Recursion Idea." }, { "code": null, "e": 25796, "s": 25618, "text": "Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray." }, { "code": null, "e": 25835, "s": 25796, "text": "Base Case: If array size is 1, return." }, { "code": null, "e": 25920, "s": 25835, "text": "Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray." }, { "code": null, "e": 25976, "s": 25920, "text": "Recur for all elements except last of current subarray." }, { "code": "// Java program for recursive implementation// of Bubble sort import java.util.Arrays; public class GFG{ // A function to implement bubble sort static void bubbleSort(int arr[], int n) { // Base case if (n == 1) return; // One pass of bubble sort. After // this pass, the largest element // is moved (or bubbled) to end. for (int i=0; i<n-1; i++) if (arr[i] > arr[i+1]) { // swap arr[i], arr[i+1] int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } // Largest element is fixed, // recur for remaining array bubbleSort(arr, n-1); } // Driver Method public static void main(String[] args) { int arr[] = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr, arr.length); System.out.println(\"Sorted array : \"); System.out.println(Arrays.toString(arr)); }}", "e": 26976, "s": 25976, "text": null }, { "code": null, "e": 27049, "s": 26976, "text": "Please refer complete article on Recursive Bubble Sort for more details!" }, { "code": null, "e": 27060, "s": 27049, "text": "BubbleSort" }, { "code": null, "e": 27074, "s": 27060, "text": "Java Programs" }, { "code": null, "e": 27082, "s": 27074, "text": "Sorting" }, { "code": null, "e": 27090, "s": 27082, "text": "Sorting" }, { "code": null, "e": 27188, "s": 27090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27220, "s": 27188, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 27249, "s": 27220, "text": "Iterate through List in Java" }, { "code": null, "e": 27293, "s": 27249, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27331, "s": 27293, "text": "Factory method design pattern in Java" }, { "code": null, "e": 27412, "s": 27331, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 27424, "s": 27412, "text": "Bubble Sort" }, { "code": null, "e": 27439, "s": 27424, "text": "Selection Sort" }, { "code": null, "e": 27462, "s": 27439, "text": "std::sort() in C++ STL" } ]
Python Set | pop() - GeeksforGeeks
08 Aug, 2021 This in-built function of Python helps to pop out elements from a set just like the principle used in the concept while implementing Stack. This method removes a top element from the set but not the random element and returns the removed element. We can verify this by printing the set before using the pop() method. Syntax: # Pops a First element from S # and returns it. S.pop() This is one of the basic functions of the set and accepts no arguments. The return value is the popped element from the set. Once the element is popped out of the set, the set loses the element and it is updated to a set without the element. Examples: Input : sets = {1, 2, 3, 4, 5} Output : 1 Updated set is {2, 3, 4, 5} Input : sets = {"ram", "rahim", "ajay", "rishav", "aakash"} Output : rahim Updated set is {'ram', 'rishav', 'ajay', 'aakash'} Python3 # Python code to illustrate pop() method S = {"ram", "rahim", "ajay", "rishav", "aakash"} # Print the set before using pop() method# First element after printing the set will be popped outprint(S) # Popping three elements and printing themprint(S.pop())print(S.pop())print(S.pop()) # The updated setprint("Updated set is", S) Output: rishav ram rahim Updated set is {'aakash', 'ajay'} On the other hand, if the set is empty, then a TypeError is returned as shown by the following program. Python3 # Python code to illustrate pop() method# on an empty setS = {} # Popping three elements and printing themprint(S.pop()) # The updated setprint("Updated set is", S) Error: Traceback (most recent call last): File "/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py", line 6, in print(S.pop()) TypeError: pop expected at least 1 arguments, got 0 hrishabhjain67 python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24366, "s": 24338, "text": "\n08 Aug, 2021" }, { "code": null, "e": 24614, "s": 24366, "text": "This in-built function of Python helps to pop out elements from a set just like the principle used in the concept while implementing Stack. This method removes a top element from the set but not the random element and returns the removed element. " }, { "code": null, "e": 24684, "s": 24614, "text": "We can verify this by printing the set before using the pop() method." }, { "code": null, "e": 24693, "s": 24684, "text": "Syntax: " }, { "code": null, "e": 24749, "s": 24693, "text": "# Pops a First element from S\n# and returns it.\nS.pop()" }, { "code": null, "e": 24992, "s": 24749, "text": "This is one of the basic functions of the set and accepts no arguments. The return value is the popped element from the set. Once the element is popped out of the set, the set loses the element and it is updated to a set without the element. " }, { "code": null, "e": 25003, "s": 24992, "text": "Examples: " }, { "code": null, "e": 25203, "s": 25003, "text": "Input : \nsets = {1, 2, 3, 4, 5}\nOutput : \n1\nUpdated set is {2, 3, 4, 5}\n\nInput : \nsets = {\"ram\", \"rahim\", \"ajay\", \"rishav\", \"aakash\"}\nOutput :\nrahim\nUpdated set is {'ram', 'rishav', 'ajay', 'aakash'}" }, { "code": null, "e": 25213, "s": 25205, "text": "Python3" }, { "code": "# Python code to illustrate pop() method S = {\"ram\", \"rahim\", \"ajay\", \"rishav\", \"aakash\"} # Print the set before using pop() method# First element after printing the set will be popped outprint(S) # Popping three elements and printing themprint(S.pop())print(S.pop())print(S.pop()) # The updated setprint(\"Updated set is\", S)", "e": 25539, "s": 25213, "text": null }, { "code": null, "e": 25548, "s": 25539, "text": "Output: " }, { "code": null, "e": 25599, "s": 25548, "text": "rishav\nram\nrahim\nUpdated set is {'aakash', 'ajay'}" }, { "code": null, "e": 25705, "s": 25599, "text": "On the other hand, if the set is empty, then a TypeError is returned as shown by the following program. " }, { "code": null, "e": 25713, "s": 25705, "text": "Python3" }, { "code": "# Python code to illustrate pop() method# on an empty setS = {} # Popping three elements and printing themprint(S.pop()) # The updated setprint(\"Updated set is\", S)", "e": 25878, "s": 25713, "text": null }, { "code": null, "e": 25886, "s": 25878, "text": "Error: " }, { "code": null, "e": 26056, "s": 25886, "text": "Traceback (most recent call last):\n File \"/home/7c5b1d5728eb9aa0e63b1d70ee5c410e.py\", line 6, in \n print(S.pop())\nTypeError: pop expected at least 1 arguments, got 0" }, { "code": null, "e": 26071, "s": 26056, "text": "hrishabhjain67" }, { "code": null, "e": 26082, "s": 26071, "text": "python-set" }, { "code": null, "e": 26089, "s": 26082, "text": "Python" }, { "code": null, "e": 26100, "s": 26089, "text": "python-set" }, { "code": null, "e": 26198, "s": 26100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26226, "s": 26198, "text": "Read JSON file using Python" }, { "code": null, "e": 26276, "s": 26226, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26298, "s": 26276, "text": "Python map() function" }, { "code": null, "e": 26342, "s": 26298, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26360, "s": 26342, "text": "Python Dictionary" }, { "code": null, "e": 26383, "s": 26360, "text": "Taking input in Python" }, { "code": null, "e": 26418, "s": 26383, "text": "Read a file line by line in Python" }, { "code": null, "e": 26450, "s": 26418, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26472, "s": 26450, "text": "Enumerate() in Python" } ]
Python - Index Value Summation List - GeeksforGeeks
27 Feb, 2020 To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that we may need to employ different strategies. This article discusses some of those strategies. Method 1 : Naive methodThis is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements. This is done using a loop. The task of performing sum is performed using external variable to add. # Python 3 code to demonstrate # Index Value Summation List# using naive method # initializing listtest_list = [1, 4, 5, 6, 7] # Printing list print ("The original list is : " + str(test_list)) # using naive method to# Index Value Summation Listres = []for i in range(len(test_list)): res.append(i + test_list[i]) print ("The list index-value summation is : " + str(res)) The original list is : [1, 4, 5, 6, 7] The list index-value summation is : [1, 5, 7, 9, 11] Method 2 : Using list comprehension + sum()This method works in similar way as the above method but uses the list comprehension technique for the same, this reduces the possible lines of code to be written and hence saves time. The task of performing summation is done by sum(). # Python 3 code to demonstrate # Index Value Summation List# using list comprehension # initializing listtest_list = [1, 4, 5, 6, 7] # Printing list print ("The original list is : " + str(test_list)) # using list comprehension to# Index Value Summation Listres = [sum(list((i, test_list[i]))) for i in range(len(test_list))] print ("The list index-value summation is : " + str(res)) The original list is : [1, 4, 5, 6, 7] The list index-value summation is : [1, 5, 7, 9, 11] Python list-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": "\n27 Feb, 2020" }, { "code": null, "e": 25823, "s": 25537, "text": "To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that we may need to employ different strategies. This article discusses some of those strategies." }, { "code": null, "e": 26094, "s": 25823, "text": "Method 1 : Naive methodThis is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements. This is done using a loop. The task of performing sum is performed using external variable to add." }, { "code": "# Python 3 code to demonstrate # Index Value Summation List# using naive method # initializing listtest_list = [1, 4, 5, 6, 7] # Printing list print (\"The original list is : \" + str(test_list)) # using naive method to# Index Value Summation Listres = []for i in range(len(test_list)): res.append(i + test_list[i]) print (\"The list index-value summation is : \" + str(res))", "e": 26473, "s": 26094, "text": null }, { "code": null, "e": 26566, "s": 26473, "text": "The original list is : [1, 4, 5, 6, 7]\nThe list index-value summation is : [1, 5, 7, 9, 11]\n" }, { "code": null, "e": 26847, "s": 26568, "text": "Method 2 : Using list comprehension + sum()This method works in similar way as the above method but uses the list comprehension technique for the same, this reduces the possible lines of code to be written and hence saves time. The task of performing summation is done by sum()." }, { "code": "# Python 3 code to demonstrate # Index Value Summation List# using list comprehension # initializing listtest_list = [1, 4, 5, 6, 7] # Printing list print (\"The original list is : \" + str(test_list)) # using list comprehension to# Index Value Summation Listres = [sum(list((i, test_list[i]))) for i in range(len(test_list))] print (\"The list index-value summation is : \" + str(res))", "e": 27234, "s": 26847, "text": null }, { "code": null, "e": 27327, "s": 27234, "text": "The original list is : [1, 4, 5, 6, 7]\nThe list index-value summation is : [1, 5, 7, 9, 11]\n" }, { "code": null, "e": 27348, "s": 27327, "text": "Python list-programs" }, { "code": null, "e": 27355, "s": 27348, "text": "Python" }, { "code": null, "e": 27371, "s": 27355, "text": "Python Programs" }, { "code": null, "e": 27469, "s": 27371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27501, "s": 27469, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27543, "s": 27501, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27585, "s": 27543, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27641, "s": 27585, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27668, "s": 27641, "text": "Python Classes and Objects" }, { "code": null, "e": 27690, "s": 27668, "text": "Defaultdict in Python" }, { "code": null, "e": 27729, "s": 27690, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27775, "s": 27729, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27813, "s": 27775, "text": "Python | Convert a list to dictionary" } ]
Matplotlib.pyplot.locator_params() in Python - GeeksforGeeks
21 Apr, 2020 Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Note: For more information, refer to Python Matplotlib – An Overview locator_params() is used for controlling the behaviors of tick locators. The attribute axis is for specifying on which axis is the function being applied. # for Y axis matplotlib.pyplot.locator_params(axis='y', nbins=3) # for X axis matplotlib.pyplot.locator_params(axis='x', nbins=3) # for both, x-axis and y-axis: Default matplotlib.pyplot.locator_params(nbins=3) Reducing the maximum number of ticks and use tight bounds: plt.locator_params(tight=True, nbins=4) Example 1: # importing librariesimport matplotlib.pyplot as plt # Y-axis Valuesy =[-1, 4, 9, 16, 25] # X-axis Valuesx =[1, 2, 3, 4, 5] plt.locator_params(axis ='x', nbins = 5) # adding grid to the plotaxes = plt.axes()axes.grid() # defining the plotplt.plot(x, y, 'mx', color ='green') # range of y-axis in the plotplt.ylim(ymin =-1.2, ymax = 30) # Set the marginsplt.margins(0.2) # printing the plotplt.show() Output: Example 2: # importing librariesimport matplotlib.pyplot as plt # defining the functiondef for_lines(xlab, ylab, plot_title, size_x, size_y, content =[]): width = len(content[0][1:]) s = [x for x in range(1, width + 1)] # specifying the size of figure plt.figure(figsize =(size_x, size_y)) for line in content: plt.plot(s, line[1:], 'ro--', color ='green', label = line[0]) # to add title to the plot plt.title(plot_title) # for adding labels to the plot plt.xlabel(xlab) plt.ylabel(ylab) t = len(s) plt.locator_params(nbins = t) for_lines("x-axis", "y-axis", "GeeksForGeeks", 7, 7, [[1, 2, 4, 3, 5]]) Output: Example 3: # importing librariesimport matplotlib.pyplot as plt plt.locator_params(nbins = 10) # defining the plotplt.plot([1, 2, 3, 5, 7], [2, 3, 9, 15, 16], 'ro-', color ='red') # printing the plotplt.show() Output: Python-matplotlib Python Write From Home 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 Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Matplotlib.pyplot.title() in Python Factory method design pattern in Java
[ { "code": null, "e": 25537, "s": 25509, "text": "\n21 Apr, 2020" }, { "code": null, "e": 25780, "s": 25537, "text": "Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.Pyplot is a collection of command style functions that make matplotlib work like MATLAB." }, { "code": null, "e": 25849, "s": 25780, "text": "Note: For more information, refer to Python Matplotlib – An Overview" }, { "code": null, "e": 26004, "s": 25849, "text": "locator_params() is used for controlling the behaviors of tick locators. The attribute axis is for specifying on which axis is the function being applied." }, { "code": null, "e": 26221, "s": 26004, "text": "# for Y axis\nmatplotlib.pyplot.locator_params(axis='y', nbins=3) \n\n# for X axis\nmatplotlib.pyplot.locator_params(axis='x', nbins=3) \n\n# for both, x-axis and y-axis: Default\nmatplotlib.pyplot.locator_params(nbins=3) \n" }, { "code": null, "e": 26280, "s": 26221, "text": "Reducing the maximum number of ticks and use tight bounds:" }, { "code": null, "e": 26321, "s": 26280, "text": "plt.locator_params(tight=True, nbins=4)\n" }, { "code": null, "e": 26332, "s": 26321, "text": "Example 1:" }, { "code": "# importing librariesimport matplotlib.pyplot as plt # Y-axis Valuesy =[-1, 4, 9, 16, 25] # X-axis Valuesx =[1, 2, 3, 4, 5] plt.locator_params(axis ='x', nbins = 5) # adding grid to the plotaxes = plt.axes()axes.grid() # defining the plotplt.plot(x, y, 'mx', color ='green') # range of y-axis in the plotplt.ylim(ymin =-1.2, ymax = 30) # Set the marginsplt.margins(0.2) # printing the plotplt.show()", "e": 26740, "s": 26332, "text": null }, { "code": null, "e": 26748, "s": 26740, "text": "Output:" }, { "code": null, "e": 26759, "s": 26748, "text": "Example 2:" }, { "code": "# importing librariesimport matplotlib.pyplot as plt # defining the functiondef for_lines(xlab, ylab, plot_title, size_x, size_y, content =[]): width = len(content[0][1:]) s = [x for x in range(1, width + 1)] # specifying the size of figure plt.figure(figsize =(size_x, size_y)) for line in content: plt.plot(s, line[1:], 'ro--', color ='green', label = line[0]) # to add title to the plot plt.title(plot_title) # for adding labels to the plot plt.xlabel(xlab) plt.ylabel(ylab) t = len(s) plt.locator_params(nbins = t) for_lines(\"x-axis\", \"y-axis\", \"GeeksForGeeks\", 7, 7, [[1, 2, 4, 3, 5]])", "e": 27469, "s": 26759, "text": null }, { "code": null, "e": 27477, "s": 27469, "text": "Output:" }, { "code": null, "e": 27488, "s": 27477, "text": "Example 3:" }, { "code": "# importing librariesimport matplotlib.pyplot as plt plt.locator_params(nbins = 10) # defining the plotplt.plot([1, 2, 3, 5, 7], [2, 3, 9, 15, 16], 'ro-', color ='red') # printing the plotplt.show()", "e": 27706, "s": 27488, "text": null }, { "code": null, "e": 27714, "s": 27706, "text": "Output:" }, { "code": null, "e": 27732, "s": 27714, "text": "Python-matplotlib" }, { "code": null, "e": 27739, "s": 27732, "text": "Python" }, { "code": null, "e": 27755, "s": 27739, "text": "Write From Home" }, { "code": null, "e": 27853, "s": 27755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27885, "s": 27853, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27927, "s": 27885, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27969, "s": 27927, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28025, "s": 27969, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28052, "s": 28025, "text": "Python Classes and Objects" }, { "code": null, "e": 28088, "s": 28052, "text": "Convert string to integer in Python" }, { "code": null, "e": 28149, "s": 28088, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28165, "s": 28149, "text": "Python infinity" }, { "code": null, "e": 28201, "s": 28165, "text": "Matplotlib.pyplot.title() in Python" } ]
Printing Heart Pattern in C - GeeksforGeeks
29 Oct, 2021 How to print below heart pattern in C? AAAAAAA AAAAAA AAAAAAAAA AAAAAAAA AAAAAAAAAAA AAAAAAAAAA AAAAAAAAAAAAA AAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBB BBBBBBBBBBBBB BBBBBBBBBBB BBBBBBBBB BBBBBBB BBBBB BBB B C++ C Java Python3 C# PHP Javascript // C++ code to print a HEART Shape#include<iostream>using namespace std; int main(){ // HERE, we have set the size of Heart, size = 15 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size/2; a <= size; a = a+2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size-a; b = b+2) cout<<" "; // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) cout<<"A"; // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size-a; b++) cout<<" "; // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a-1; b++) cout<<"A"; cout<<endl; } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) cout<<" "; // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) cout<<"B"; cout<<endl; }}// This code is contributed by Kunal Mali. // C code to print a HEART Shape#include<stdio.h> int main(){ // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size/2; a <= size; a = a+2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size-a; b = b+2) printf(" "); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) printf("A"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size-a; b++) printf(" "); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a-1; b++) printf("A"); printf("\n"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) printf(" "); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) printf("B"); printf("\n"); }} // Java code to print a HEART Shape class GFG { public static void main(String arg[]) { // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size / 2; a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) System.out.print(" "); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) System.out.print("A"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) System.out.print(" "); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) System.out.print("A"); System.out.print("\n"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) System.out.print(" "); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) System.out.print("B"); System.out.print("\n"); }}} // This code is contributed by Anant Agarwal. # Python 3 code to print a HEART Shape # HERE, we have set the size of Heart,# size = 10size = 15 # FOR THE APEX OF HEARTfor a in range(int(size / 2), size + 1, 2): # FOR SPACE BEFORE PEAK-1 : PART 1 for b in range(1, size - a, 2): print(" ", end = "") # FOR PRINTING PEAK-1 : PART 2 for b in range(1, a + 1): print("A",end="") # FOR SPACE B/W PEAK-1 AND PEAK-2 : # PART 3 for b in range(1, (size - a) + 1): print(" ", end = "") # FOR PRINTING PEAK-2 : PART 4 for b in range(1, a): print("A", end = "") print("") # FOR THE BASE OF HEART ie. THE INVERTED# TRIANGLEfor a in range(size, -1, -1): # FOR SPACE BEFORE THE INVERTED TRIANGLE:# PART 5 for b in range(a, size): print(" ", end = "") # FOR PRINTING THE BASE OF TRIANGLE: # PART 6 for b in range(1, (a * 2)): print("B", end = "") print("") # This code is contributed by Smitha. // Java code to print a HEART Shapeusing System; class GFG { public static void Main() { // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size / 2; a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) Console.Write(" "); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) Console.Write("A"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) Console.Write(" "); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) Console.Write("A"); Console.WriteLine(); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) Console.Write(" "); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) Console.Write("B"); Console.WriteLine(""); }}} // This code is contributed by vt_m. <?php // php code to print a HEART Shape // HERE, we have set the size // of Heart, size = 10 $size = 15; // FOR THE APEX OF HEART for ($a = floor($size / 2); $a <= $size; $a = $a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for ($b = 1; $b < $size-$a; $b = $b + 2) printf(" "); // FOR PRINTING PEAK-1 : PART 2 for ($b = 1; $b <= $a; $b++) printf("A"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for ($b = 1; $b <= $size-$a; $b++) printf(" "); // FOR PRINTING PEAK-2 : PART 4 for ($b = 1; $b <= $a - 1; $b++) printf("A"); printf("\n"); } // FOR THE BASE OF HEART ie. // THE INVERTED TRIANGLE for ($a = $size; $a >= 0; $a--) { // FOR SPACE BEFORE THE // INVERTED TRIANGLE : PART 5 for ($b = $a; $b < $size; $b++) printf(" "); // FOR PRINTING THE BASE // OF TRIANGLE : PART 6 for ($b = 1; $b <= (($a * 2) - 1); $b++) printf("B"); printf("\n"); } // This code is contributed by mits ?> <script> // javascript code to print a HEART Shape // HERE, we have set the size of Heart, size = 10 var a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = parseInt(size / 2); a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) document.write(" "); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) document.write("A"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) document.write(" "); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) document.write("A"); document.write("<br>"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) document.write(" "); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) document.write("B"); document.write("<br>"); } // This code contributed by Princi Singh</script> Output : AAAAAAA AAAAAA AAAAAAAAA AAAAAAAA AAAAAAAAAAA AAAAAAAAAA AAAAAAAAAAAAA AAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBB BBBBBBBBBBBBB BBBBBBBBBBB BBBBBBBBB BBBBBBB BBBBB BBB B This article is contributed by Mohit Gupta . 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. Mithun Kumar Smitha Dinesh Semwal Akanksha_Rai kunalmali princi singh Kirti_Mangal cpp-puzzle pattern-printing C++ School Programming pattern-printing CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Python Dictionary Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 25961, "s": 25933, "text": "\n29 Oct, 2021" }, { "code": null, "e": 26000, "s": 25961, "text": "How to print below heart pattern in C?" }, { "code": null, "e": 26485, "s": 26000, "text": " AAAAAAA AAAAAA\n AAAAAAAAA AAAAAAAA\n AAAAAAAAAAA AAAAAAAAAA\n AAAAAAAAAAAAA AAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBB\n BBBBBBBBBBBBB\n BBBBBBBBBBB\n BBBBBBBBB\n BBBBBBB\n BBBBB\n BBB\n B" }, { "code": null, "e": 26489, "s": 26485, "text": "C++" }, { "code": null, "e": 26491, "s": 26489, "text": "C" }, { "code": null, "e": 26496, "s": 26491, "text": "Java" }, { "code": null, "e": 26504, "s": 26496, "text": "Python3" }, { "code": null, "e": 26507, "s": 26504, "text": "C#" }, { "code": null, "e": 26511, "s": 26507, "text": "PHP" }, { "code": null, "e": 26522, "s": 26511, "text": "Javascript" }, { "code": "// C++ code to print a HEART Shape#include<iostream>using namespace std; int main(){ // HERE, we have set the size of Heart, size = 15 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size/2; a <= size; a = a+2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size-a; b = b+2) cout<<\" \"; // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) cout<<\"A\"; // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size-a; b++) cout<<\" \"; // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a-1; b++) cout<<\"A\"; cout<<endl; } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) cout<<\" \"; // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) cout<<\"B\"; cout<<endl; }}// This code is contributed by Kunal Mali.", "e": 27628, "s": 26522, "text": null }, { "code": "// C code to print a HEART Shape#include<stdio.h> int main(){ // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size/2; a <= size; a = a+2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size-a; b = b+2) printf(\" \"); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) printf(\"A\"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size-a; b++) printf(\" \"); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a-1; b++) printf(\"A\"); printf(\"\\n\"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) printf(\" \"); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) printf(\"B\"); printf(\"\\n\"); }}", "e": 28662, "s": 27628, "text": null }, { "code": "// Java code to print a HEART Shape class GFG { public static void main(String arg[]) { // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size / 2; a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) System.out.print(\" \"); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) System.out.print(\"A\"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) System.out.print(\" \"); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) System.out.print(\"A\"); System.out.print(\"\\n\"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) System.out.print(\" \"); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) System.out.print(\"B\"); System.out.print(\"\\n\"); }}} // This code is contributed by Anant Agarwal.", "e": 29785, "s": 28662, "text": null }, { "code": "# Python 3 code to print a HEART Shape # HERE, we have set the size of Heart,# size = 10size = 15 # FOR THE APEX OF HEARTfor a in range(int(size / 2), size + 1, 2): # FOR SPACE BEFORE PEAK-1 : PART 1 for b in range(1, size - a, 2): print(\" \", end = \"\") # FOR PRINTING PEAK-1 : PART 2 for b in range(1, a + 1): print(\"A\",end=\"\") # FOR SPACE B/W PEAK-1 AND PEAK-2 : # PART 3 for b in range(1, (size - a) + 1): print(\" \", end = \"\") # FOR PRINTING PEAK-2 : PART 4 for b in range(1, a): print(\"A\", end = \"\") print(\"\") # FOR THE BASE OF HEART ie. THE INVERTED# TRIANGLEfor a in range(size, -1, -1): # FOR SPACE BEFORE THE INVERTED TRIANGLE:# PART 5 for b in range(a, size): print(\" \", end = \"\") # FOR PRINTING THE BASE OF TRIANGLE: # PART 6 for b in range(1, (a * 2)): print(\"B\", end = \"\") print(\"\") # This code is contributed by Smitha.", "e": 30743, "s": 29785, "text": null }, { "code": "// Java code to print a HEART Shapeusing System; class GFG { public static void Main() { // HERE, we have set the size of Heart, size = 10 int a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = size / 2; a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) Console.Write(\" \"); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) Console.Write(\"A\"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) Console.Write(\" \"); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) Console.Write(\"A\"); Console.WriteLine(); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) Console.Write(\" \"); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) Console.Write(\"B\"); Console.WriteLine(\"\"); }}} // This code is contributed by vt_m.", "e": 31836, "s": 30743, "text": null }, { "code": "<?php // php code to print a HEART Shape // HERE, we have set the size // of Heart, size = 10 $size = 15; // FOR THE APEX OF HEART for ($a = floor($size / 2); $a <= $size; $a = $a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for ($b = 1; $b < $size-$a; $b = $b + 2) printf(\" \"); // FOR PRINTING PEAK-1 : PART 2 for ($b = 1; $b <= $a; $b++) printf(\"A\"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for ($b = 1; $b <= $size-$a; $b++) printf(\" \"); // FOR PRINTING PEAK-2 : PART 4 for ($b = 1; $b <= $a - 1; $b++) printf(\"A\"); printf(\"\\n\"); } // FOR THE BASE OF HEART ie. // THE INVERTED TRIANGLE for ($a = $size; $a >= 0; $a--) { // FOR SPACE BEFORE THE // INVERTED TRIANGLE : PART 5 for ($b = $a; $b < $size; $b++) printf(\" \"); // FOR PRINTING THE BASE // OF TRIANGLE : PART 6 for ($b = 1; $b <= (($a * 2) - 1); $b++) printf(\"B\"); printf(\"\\n\"); } // This code is contributed by mits ?>", "e": 33019, "s": 31836, "text": null }, { "code": "<script> // javascript code to print a HEART Shape // HERE, we have set the size of Heart, size = 10 var a, b, size = 15; /* FOR THE APEX OF HEART */ for (a = parseInt(size / 2); a <= size; a = a + 2) { // FOR SPACE BEFORE PEAK-1 : PART 1 for (b = 1; b < size - a; b = b + 2) document.write(\" \"); // FOR PRINTING PEAK-1 : PART 2 for (b = 1; b <= a; b++) document.write(\"A\"); // FOR SPACE B/W PEAK-1 AND PEAK-2 : PART 3 for (b = 1; b <= size - a; b++) document.write(\" \"); // FOR PRINTING PEAK-2 : PART 4 for (b = 1; b <= a - 1; b++) document.write(\"A\"); document.write(\"<br>\"); } /*FOR THE BASE OF HEART ie. THE INVERTED TRIANGLE */ for (a = size; a >= 0; a--) { // FOR SPACE BEFORE THE INVERTED TRIANGLE : PART 5 for (b = a; b < size; b++) document.write(\" \"); // FOR PRINTING THE BASE OF TRIANGLE : PART 6 for (b = 1; b <= ((a * 2) - 1); b++) document.write(\"B\"); document.write(\"<br>\"); } // This code contributed by Princi Singh</script>", "e": 34106, "s": 33019, "text": null }, { "code": null, "e": 34116, "s": 34106, "text": "Output : " }, { "code": null, "e": 34601, "s": 34116, "text": " AAAAAAA AAAAAA\n AAAAAAAAA AAAAAAAA\n AAAAAAAAAAA AAAAAAAAAA\n AAAAAAAAAAAAA AAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBBBB\n BBBBBBBBBBBBBBB\n BBBBBBBBBBBBB\n BBBBBBBBBBB\n BBBBBBBBB\n BBBBBBB\n BBBBB\n BBB\n B" }, { "code": null, "e": 35022, "s": 34601, "text": "This article is contributed by Mohit Gupta . 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": 35035, "s": 35022, "text": "Mithun Kumar" }, { "code": null, "e": 35056, "s": 35035, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 35069, "s": 35056, "text": "Akanksha_Rai" }, { "code": null, "e": 35079, "s": 35069, "text": "kunalmali" }, { "code": null, "e": 35092, "s": 35079, "text": "princi singh" }, { "code": null, "e": 35105, "s": 35092, "text": "Kirti_Mangal" }, { "code": null, "e": 35116, "s": 35105, "text": "cpp-puzzle" }, { "code": null, "e": 35133, "s": 35116, "text": "pattern-printing" }, { "code": null, "e": 35137, "s": 35133, "text": "C++" }, { "code": null, "e": 35156, "s": 35137, "text": "School Programming" }, { "code": null, "e": 35173, "s": 35156, "text": "pattern-printing" }, { "code": null, "e": 35177, "s": 35173, "text": "CPP" }, { "code": null, "e": 35275, "s": 35177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35294, "s": 35275, "text": "Inheritance in C++" }, { "code": null, "e": 35318, "s": 35294, "text": "C++ Classes and Objects" }, { "code": null, "e": 35342, "s": 35318, "text": "Virtual Function in C++" }, { "code": null, "e": 35362, "s": 35342, "text": "Constructors in C++" }, { "code": null, "e": 35393, "s": 35362, "text": "Templates in C++ with Examples" }, { "code": null, "e": 35411, "s": 35393, "text": "Python Dictionary" }, { "code": null, "e": 35430, "s": 35411, "text": "Inheritance in C++" }, { "code": null, "e": 35455, "s": 35430, "text": "Reverse a string in Java" }, { "code": null, "e": 35479, "s": 35455, "text": "C++ Classes and Objects" } ]
Python | Playing audio file in Pygame - GeeksforGeeks
27 Feb, 2020 Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Note: For more information, refer to Introduction to pygame In order to play music/audio files in pygame, pygame.mixer is used (pygame module for loading and playing sounds). This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so: Starting the mixermixer.init() mixer.init() Loading the song.mixer.music.load("song.mp3") mixer.music.load("song.mp3") Setting the volume.mixer.music.set_volume(0.7) mixer.music.set_volume(0.7) Start playing the song.mixer.music.play() mixer.music.play() Below is the implementation. from pygame import mixer # Starting the mixermixer.init() # Loading the songmixer.music.load("song.mp3") # Setting the volumemixer.music.set_volume(0.7) # Start playing the songmixer.music.play() # infinite loopwhile True: print("Press 'p' to pause, 'r' to resume") print("Press 'e' to exit the program") query = input(" ") if query == 'p': # Pausing the music mixer.music.pause() elif query == 'r': # Resuming the music mixer.music.unpause() elif query == 'e': # Stop the mixer mixer.music.stop() break Output: This code will also play the “song.mp3” file. Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25687, "s": 25659, "text": "\n27 Feb, 2020" }, { "code": null, "e": 25993, "s": 25687, "text": "Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so." }, { "code": null, "e": 26053, "s": 25993, "text": "Note: For more information, refer to Introduction to pygame" }, { "code": null, "e": 26299, "s": 26053, "text": "In order to play music/audio files in pygame, pygame.mixer is used (pygame module for loading and playing sounds). This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so:" }, { "code": null, "e": 26330, "s": 26299, "text": "Starting the mixermixer.init()" }, { "code": null, "e": 26343, "s": 26330, "text": "mixer.init()" }, { "code": null, "e": 26389, "s": 26343, "text": "Loading the song.mixer.music.load(\"song.mp3\")" }, { "code": null, "e": 26418, "s": 26389, "text": "mixer.music.load(\"song.mp3\")" }, { "code": null, "e": 26465, "s": 26418, "text": "Setting the volume.mixer.music.set_volume(0.7)" }, { "code": null, "e": 26493, "s": 26465, "text": "mixer.music.set_volume(0.7)" }, { "code": null, "e": 26535, "s": 26493, "text": "Start playing the song.mixer.music.play()" }, { "code": null, "e": 26554, "s": 26535, "text": "mixer.music.play()" }, { "code": null, "e": 26583, "s": 26554, "text": "Below is the implementation." }, { "code": "from pygame import mixer # Starting the mixermixer.init() # Loading the songmixer.music.load(\"song.mp3\") # Setting the volumemixer.music.set_volume(0.7) # Start playing the songmixer.music.play() # infinite loopwhile True: print(\"Press 'p' to pause, 'r' to resume\") print(\"Press 'e' to exit the program\") query = input(\" \") if query == 'p': # Pausing the music mixer.music.pause() elif query == 'r': # Resuming the music mixer.music.unpause() elif query == 'e': # Stop the mixer mixer.music.stop() break", "e": 27183, "s": 26583, "text": null }, { "code": null, "e": 27191, "s": 27183, "text": "Output:" }, { "code": null, "e": 27237, "s": 27191, "text": "This code will also play the “song.mp3” file." }, { "code": null, "e": 27251, "s": 27237, "text": "Python-PyGame" }, { "code": null, "e": 27258, "s": 27251, "text": "Python" }, { "code": null, "e": 27356, "s": 27258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27374, "s": 27356, "text": "Python Dictionary" }, { "code": null, "e": 27409, "s": 27374, "text": "Read a file line by line in Python" }, { "code": null, "e": 27441, "s": 27409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27463, "s": 27441, "text": "Enumerate() in Python" }, { "code": null, "e": 27505, "s": 27463, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27535, "s": 27505, "text": "Iterate over a list in Python" }, { "code": null, "e": 27561, "s": 27535, "text": "Python String | replace()" }, { "code": null, "e": 27590, "s": 27561, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27634, "s": 27590, "text": "Reading and Writing to text files in Python" } ]
How to merge a transparent PNG image with another image using PIL? - GeeksforGeeks
03 Mar, 2021 This article discusses how to put a transparent PNG image with another image. This is a very common operation on images. It has a lot of different applications. For example, adding a watermark or logo on an image. To do this, we are using the PIL module in Python. In which we use some inbuilt methods and combine the images in such a way that it looks to be pasted. Open Function – It is used to open an image. Convert Function – It returns a converted copy of a given image. It converts the image to its true color with a transparency mask. Paste Function – It is used to paste an image on another image. Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None)OR image_object.paste(image_2, box=None, mask=None) Parameters: image_1/image_object : It is the image on which other image is to be pasted. image_2: Source image or pixel value (integer or tuple). box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. mask: a mask that will be used to paste the image. If you pass an image with transparency, then the alpha channel is used as the mask. Approach: Open the front and background image using Image.open() function. Convert both the image to RGBA. Calculate the position where you want to paste the image. Use the paste function to merge the two images. Save the image. Input Data: To input the data, we are using two images: Front Image: A transparent image like a logo Background image: For background like any wallpaper image Implementation: Python3 # import PIL modulefrom PIL import Image # Front Imagefilename = 'front.png' # Back Imagefilename1 = 'back.jpg' # Open Front ImagefrontImage = Image.open(filename) # Open Background Imagebackground = Image.open(filename1) # Convert image to RGBAfrontImage = frontImage.convert("RGBA") # Convert image to RGBAbackground = background.convert("RGBA") # Calculate width to be at the centerwidth = (background.width - frontImage.width) // 2 # Calculate height to be at the centerheight = (background.height - frontImage.height) // 2 # Paste the frontImage at (width, height)background.paste(frontImage, (width, height), frontImage) # Save this imagebackground.save("new.png", format="png") Output: Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n03 Mar, 2021" }, { "code": null, "e": 25922, "s": 25555, "text": "This article discusses how to put a transparent PNG image with another image. This is a very common operation on images. It has a lot of different applications. For example, adding a watermark or logo on an image. To do this, we are using the PIL module in Python. In which we use some inbuilt methods and combine the images in such a way that it looks to be pasted." }, { "code": null, "e": 25967, "s": 25922, "text": "Open Function – It is used to open an image." }, { "code": null, "e": 26098, "s": 25967, "text": "Convert Function – It returns a converted copy of a given image. It converts the image to its true color with a transparency mask." }, { "code": null, "e": 26163, "s": 26098, "text": "Paste Function – It is used to paste an image on another image. " }, { "code": null, "e": 26283, "s": 26163, "text": "Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None)OR image_object.paste(image_2, box=None, mask=None)" }, { "code": null, "e": 26295, "s": 26283, "text": "Parameters:" }, { "code": null, "e": 26372, "s": 26295, "text": "image_1/image_object : It is the image on which other image is to be pasted." }, { "code": null, "e": 26429, "s": 26372, "text": "image_2: Source image or pixel value (integer or tuple)." }, { "code": null, "e": 26625, "s": 26429, "text": "box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it’s treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner." }, { "code": null, "e": 26760, "s": 26625, "text": "mask: a mask that will be used to paste the image. If you pass an image with transparency, then the alpha channel is used as the mask." }, { "code": null, "e": 26770, "s": 26760, "text": "Approach:" }, { "code": null, "e": 26835, "s": 26770, "text": "Open the front and background image using Image.open() function." }, { "code": null, "e": 26867, "s": 26835, "text": "Convert both the image to RGBA." }, { "code": null, "e": 26925, "s": 26867, "text": "Calculate the position where you want to paste the image." }, { "code": null, "e": 26973, "s": 26925, "text": "Use the paste function to merge the two images." }, { "code": null, "e": 26989, "s": 26973, "text": "Save the image." }, { "code": null, "e": 27001, "s": 26989, "text": "Input Data:" }, { "code": null, "e": 27045, "s": 27001, "text": "To input the data, we are using two images:" }, { "code": null, "e": 27090, "s": 27045, "text": "Front Image: A transparent image like a logo" }, { "code": null, "e": 27148, "s": 27090, "text": "Background image: For background like any wallpaper image" }, { "code": null, "e": 27164, "s": 27148, "text": "Implementation:" }, { "code": null, "e": 27172, "s": 27164, "text": "Python3" }, { "code": "# import PIL modulefrom PIL import Image # Front Imagefilename = 'front.png' # Back Imagefilename1 = 'back.jpg' # Open Front ImagefrontImage = Image.open(filename) # Open Background Imagebackground = Image.open(filename1) # Convert image to RGBAfrontImage = frontImage.convert(\"RGBA\") # Convert image to RGBAbackground = background.convert(\"RGBA\") # Calculate width to be at the centerwidth = (background.width - frontImage.width) // 2 # Calculate height to be at the centerheight = (background.height - frontImage.height) // 2 # Paste the frontImage at (width, height)background.paste(frontImage, (width, height), frontImage) # Save this imagebackground.save(\"new.png\", format=\"png\")", "e": 27867, "s": 27172, "text": null }, { "code": null, "e": 27875, "s": 27867, "text": "Output:" }, { "code": null, "e": 27882, "s": 27875, "text": "Picked" }, { "code": null, "e": 27893, "s": 27882, "text": "Python-pil" }, { "code": null, "e": 27900, "s": 27893, "text": "Python" }, { "code": null, "e": 27998, "s": 27900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28030, "s": 27998, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28072, "s": 28030, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28114, "s": 28072, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28170, "s": 28114, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28197, "s": 28170, "text": "Python Classes and Objects" }, { "code": null, "e": 28228, "s": 28197, "text": "Python | os.path.join() method" }, { "code": null, "e": 28267, "s": 28228, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28296, "s": 28267, "text": "Create a directory in Python" }, { "code": null, "e": 28318, "s": 28296, "text": "Defaultdict in Python" } ]
Python - Integers String to Integer List - GeeksforGeeks
05 Sep, 2020 Given a Integers String, composed of negative and positive numbers, convert to integer list. Input : test_str = ‘4 5 -3 2 -100 -2’Output : [4, 5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list. Input : test_str = ‘-4 -5 -3 2 -100 -2’Output : [-4, -5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list. Method #1 : Using list comprehension + int() + split() In this, we split integers using split() and int() is used to integral conversion. Elements inserted in List using list comprehension Python3 # Python3 code to demonstrate working of # Integers String to Integer List# Using list comprehension + int() + split()import string # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9' # printing original stringprint("The original string is : " + str(test_str)) # int() converts to required integersres = [int(ele) for ele in test_str.split()] # printing result print("Converted Integers : " + str(res)) The original string is : 4 5 -3 2 -100 -2 -4 9 Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9] Method #2 : Using map() + int() In this, the task of extension of logic of integer conversion is done using map(). Python3 # Python3 code to demonstrate working of # Integers String to Integer List# Using map() + int()import string # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9' # printing original stringprint("The original string is : " + str(test_str)) # int() converts to required integers# map() extends logic of int to each splitres = list(map(int, test_str.split())) # printing result print("Converted Integers : " + str(res)) The original string is : 4 5 -3 2 -100 -2 -4 9 Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25557, "s": 25529, "text": "\n05 Sep, 2020" }, { "code": null, "e": 25650, "s": 25557, "text": "Given a Integers String, composed of negative and positive numbers, convert to integer list." }, { "code": null, "e": 25798, "s": 25650, "text": "Input : test_str = ‘4 5 -3 2 -100 -2’Output : [4, 5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list." }, { "code": null, "e": 25950, "s": 25798, "text": "Input : test_str = ‘-4 -5 -3 2 -100 -2’Output : [-4, -5, -3, 2, -100, -2]Explanation : Negative and positive string numbers converted to integers list." }, { "code": null, "e": 26005, "s": 25950, "text": "Method #1 : Using list comprehension + int() + split()" }, { "code": null, "e": 26139, "s": 26005, "text": "In this, we split integers using split() and int() is used to integral conversion. Elements inserted in List using list comprehension" }, { "code": null, "e": 26147, "s": 26139, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Integers String to Integer List# Using list comprehension + int() + split()import string # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9' # printing original stringprint(\"The original string is : \" + str(test_str)) # int() converts to required integersres = [int(ele) for ele in test_str.split()] # printing result print(\"Converted Integers : \" + str(res)) ", "e": 26563, "s": 26147, "text": null }, { "code": null, "e": 26663, "s": 26563, "text": "The original string is : 4 5 -3 2 -100 -2 -4 9\nConverted Integers : [4, 5, -3, 2, -100, -2, -4, 9]\n" }, { "code": null, "e": 26695, "s": 26663, "text": "Method #2 : Using map() + int()" }, { "code": null, "e": 26778, "s": 26695, "text": "In this, the task of extension of logic of integer conversion is done using map()." }, { "code": null, "e": 26786, "s": 26778, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Integers String to Integer List# Using map() + int()import string # initializing stringtest_str = '4 5 -3 2 -100 -2 -4 9' # printing original stringprint(\"The original string is : \" + str(test_str)) # int() converts to required integers# map() extends logic of int to each splitres = list(map(int, test_str.split())) # printing result print(\"Converted Integers : \" + str(res)) ", "e": 27215, "s": 26786, "text": null }, { "code": null, "e": 27315, "s": 27215, "text": "The original string is : 4 5 -3 2 -100 -2 -4 9\nConverted Integers : [4, 5, -3, 2, -100, -2, -4, 9]\n" }, { "code": null, "e": 27338, "s": 27315, "text": "Python string-programs" }, { "code": null, "e": 27345, "s": 27338, "text": "Python" }, { "code": null, "e": 27361, "s": 27345, "text": "Python Programs" }, { "code": null, "e": 27459, "s": 27361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27494, "s": 27459, "text": "Read a file line by line in Python" }, { "code": null, "e": 27526, "s": 27494, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27548, "s": 27526, "text": "Enumerate() in Python" }, { "code": null, "e": 27590, "s": 27548, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27620, "s": 27590, "text": "Iterate over a list in Python" }, { "code": null, "e": 27663, "s": 27620, "text": "Python program to convert a list to string" }, { "code": null, "e": 27685, "s": 27663, "text": "Defaultdict in Python" }, { "code": null, "e": 27724, "s": 27685, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27770, "s": 27724, "text": "Python | Split string into list of characters" } ]
How to focus on the next field input in ReactJS ? - GeeksforGeeks
08 Apr, 2021 If we want to focus on the text input field when the current input field reaches its max character capacity, we have to find the next input HTML element and make it focus. Each time the user types in the current text field, we have to check whether the field has a max character that is specified. If yes, then we have to focus on the text input field. We can use focus() function to focus the particular input field. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder, i.e., foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Example: We can see in the code, whenever we type in the input field, the handleChange function will be called, and it will decide whether the next field should be the focus or not based on the number of characters typed in the current input field. If it reaches max character then it will find the next field and make it focus. This is how the next input field focuses when the current input field hits the max characters limit. App.js import React from "react"; class App extends React.Component { render() { return ( <div> <InputFields></InputFields> </div> ); }} class InputFields extends React.Component { handleChange = (e) => { const { maxLength, value, name } = e.target; const [fieldName, fieldIndex] = name.split("-"); let fieldIntIndex = parseInt(fieldIndex, 10); // Check if no of char in field == maxlength if (value.length >= maxLength) { // It should not be last input field if (fieldIntIndex < 3) { // Get the next input field using it's name const nextfield = document.querySelector( `input[name=field-${fieldIntIndex + 1}]` ); // If found, focus the next field if (nextfield !== null) { nextfield.focus(); } } } }; render() { return ( <div style={{ padding: 30 }}> <InputFild name="field-1" length="3" handleChange={this.handleChange} /> <InputFild name="field-2" length="4" handleChange={this.handleChange} /> <InputFild name="field-3" length="3" handleChange={this.handleChange} /> </div> ); }}class InputFild extends React.Component { render() { return ( <input style={{ margin: 10 }} type="text" name={this.props.name} maxLength={this.props.length} onChange={this.props.handleChange} ></input> ); }} export default App; Output: javascript-functions Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n08 Apr, 2021" }, { "code": null, "e": 26489, "s": 26071, "text": "If we want to focus on the text input field when the current input field reaches its max character capacity, we have to find the next input HTML element and make it focus. Each time the user types in the current text field, we have to check whether the field has a max character that is specified. If yes, then we have to focus on the text input field. We can use focus() function to focus the particular input field." }, { "code": null, "e": 26517, "s": 26489, "text": "Creating React Application:" }, { "code": null, "e": 26581, "s": 26517, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26613, "s": 26581, "text": "npx create-react-app foldername" }, { "code": null, "e": 26715, "s": 26613, "text": "Step 2: After creating your project folder, i.e., foldername, move to it using the following command:" }, { "code": null, "e": 26729, "s": 26715, "text": "cd foldername" }, { "code": null, "e": 26781, "s": 26729, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27211, "s": 26781, "text": "Example: We can see in the code, whenever we type in the input field, the handleChange function will be called, and it will decide whether the next field should be the focus or not based on the number of characters typed in the current input field. If it reaches max character then it will find the next field and make it focus. This is how the next input field focuses when the current input field hits the max characters limit." }, { "code": null, "e": 27218, "s": 27211, "text": "App.js" }, { "code": "import React from \"react\"; class App extends React.Component { render() { return ( <div> <InputFields></InputFields> </div> ); }} class InputFields extends React.Component { handleChange = (e) => { const { maxLength, value, name } = e.target; const [fieldName, fieldIndex] = name.split(\"-\"); let fieldIntIndex = parseInt(fieldIndex, 10); // Check if no of char in field == maxlength if (value.length >= maxLength) { // It should not be last input field if (fieldIntIndex < 3) { // Get the next input field using it's name const nextfield = document.querySelector( `input[name=field-${fieldIntIndex + 1}]` ); // If found, focus the next field if (nextfield !== null) { nextfield.focus(); } } } }; render() { return ( <div style={{ padding: 30 }}> <InputFild name=\"field-1\" length=\"3\" handleChange={this.handleChange} /> <InputFild name=\"field-2\" length=\"4\" handleChange={this.handleChange} /> <InputFild name=\"field-3\" length=\"3\" handleChange={this.handleChange} /> </div> ); }}class InputFild extends React.Component { render() { return ( <input style={{ margin: 10 }} type=\"text\" name={this.props.name} maxLength={this.props.length} onChange={this.props.handleChange} ></input> ); }} export default App;", "e": 28707, "s": 27218, "text": null }, { "code": null, "e": 28715, "s": 28707, "text": "Output:" }, { "code": null, "e": 28736, "s": 28715, "text": "javascript-functions" }, { "code": null, "e": 28743, "s": 28736, "text": "Picked" }, { "code": null, "e": 28759, "s": 28743, "text": "React-Questions" }, { "code": null, "e": 28767, "s": 28759, "text": "ReactJS" }, { "code": null, "e": 28784, "s": 28767, "text": "Web Technologies" }, { "code": null, "e": 28882, "s": 28784, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28909, "s": 28882, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28951, "s": 28909, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28989, "s": 28951, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 29024, "s": 28989, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29082, "s": 29024, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29122, "s": 29082, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29155, "s": 29122, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29200, "s": 29155, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29250, "s": 29200, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python - Extract Row with any Boolean True - GeeksforGeeks
11 Oct, 2020 Given a Boolean Matrix, extract row which contains at least one boolean True value. Input : test_list = [[False, False], [True, True, True], [False, True], [False]] Output : [[True, True, True], [False, True]] Explanation : All rows with atleast 1 True extracted. Input : test_list = [[False, False], [False]] Output : [] Explanation : No rows with even one True. Method #1 : Using list comprehension + any() In this, we check for any element to be boolean true using any() and list comprehension is used for task of iteration of rows in matrix. Python3 # Python3 code to demonstrate working of # Extract Row with any Boolean True# Using list comprehension + any() # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]] # printing original listprint("The original list is : " + str(test_list)) # using any() to check for any True value res = [sub for sub in test_list if any(ele for ele in sub)] # printing result print("Extracted Rows : " + str(res)) Output: The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]] Method #2 : Using any() + filter() + lambda In this, we perform task of checking for any True value using any() and filter() and lambda is used to filter out matching rows. Python3 # Python3 code to demonstrate working of # Extract Row with any Boolean True# Using any() + filter() + lambda # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]] # printing original listprint("The original list is : " + str(test_list)) # using any() to check for any True value # filter() to perform filteringres = list(filter(lambda sub : any(ele for ele in sub), test_list)) # printing result print("Extracted Rows : " + str(res)) Output: The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]] Python list-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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe 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": "\n11 Oct, 2020" }, { "code": null, "e": 25621, "s": 25537, "text": "Given a Boolean Matrix, extract row which contains at least one boolean True value." }, { "code": null, "e": 25801, "s": 25621, "text": "Input : test_list = [[False, False], [True, True, True], [False, True], [False]] Output : [[True, True, True], [False, True]] Explanation : All rows with atleast 1 True extracted." }, { "code": null, "e": 25903, "s": 25801, "text": "Input : test_list = [[False, False], [False]] Output : [] Explanation : No rows with even one True. " }, { "code": null, "e": 25948, "s": 25903, "text": "Method #1 : Using list comprehension + any()" }, { "code": null, "e": 26085, "s": 25948, "text": "In this, we check for any element to be boolean true using any() and list comprehension is used for task of iteration of rows in matrix." }, { "code": null, "e": 26093, "s": 26085, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Extract Row with any Boolean True# Using list comprehension + any() # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]] # printing original listprint(\"The original list is : \" + str(test_list)) # using any() to check for any True value res = [sub for sub in test_list if any(ele for ele in sub)] # printing result print(\"Extracted Rows : \" + str(res))", "e": 26532, "s": 26093, "text": null }, { "code": null, "e": 26540, "s": 26532, "text": "Output:" }, { "code": null, "e": 26677, "s": 26540, "text": "The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]" }, { "code": null, "e": 26721, "s": 26677, "text": "Method #2 : Using any() + filter() + lambda" }, { "code": null, "e": 26850, "s": 26721, "text": "In this, we perform task of checking for any True value using any() and filter() and lambda is used to filter out matching rows." }, { "code": null, "e": 26858, "s": 26850, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Extract Row with any Boolean True# Using any() + filter() + lambda # initializing listtest_list = [[False, False], [True, True, True], [False, True], [False]] # printing original listprint(\"The original list is : \" + str(test_list)) # using any() to check for any True value # filter() to perform filteringres = list(filter(lambda sub : any(ele for ele in sub), test_list)) # printing result print(\"Extracted Rows : \" + str(res))", "e": 27335, "s": 26858, "text": null }, { "code": null, "e": 27343, "s": 27335, "text": "Output:" }, { "code": null, "e": 27480, "s": 27343, "text": "The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]" }, { "code": null, "e": 27501, "s": 27480, "text": "Python list-programs" }, { "code": null, "e": 27508, "s": 27501, "text": "Python" }, { "code": null, "e": 27524, "s": 27508, "text": "Python Programs" }, { "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 dictionary keys as a list" }, { "code": null, "e": 27928, "s": 27882, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27966, "s": 27928, "text": "Python | Convert a list to dictionary" } ]
What is SGML ? - GeeksforGeeks
20 Aug, 2021 In this article, we are going to learn about SGML.SGML stands for Standard generalized markup language is a Standard generalized markup language that makes use of a superset of extensively used markup languages like HTML and XML. It is used for marking up files and has the gain of now no longer be depending on a particular application. It is basically derived from GML (Generalized Markup Language), which allowed users to work on standardized formatting styles for electronic documents. It was developed and standardized by the International Organization for Standards (ISO) in 1986. SGML specifies the rules for tagging elements. These tags can then be interpreted to layout factors in specific ways. It is used extensively to manipulate massive files which are a concern with common revisions and want to be published in one-of-a-kind formats due to the fact it’s far a massive and complicated system, it isn’t always but extensively used on private computers. Components of SGML: SGML provides a way of describing the relationships between these entities, elements, and attributes, and tells the computer how it can recognize the component parts of a document and it is based on the concept of a document being composed of a series of entities (object). It provides rules that allow the computer to recognize where the various elements of a text entity start and end. Document Type Definition (DTD) in SGML is used to describe each element of the document in a form that the computer can understand. SGML is the simplest medium to produce files that can be read by people and exchanged between machines and applications in a straightforward manner. It is easy to understand by the human as well as the machine. Structure of SGML: <mainObject> <subObject> </subObject> </mainObject> The extension of SGML files is: File_Name.sgml Syntax: <NAME TYPE="user"> Geeks for Geeks </NAME> Example 1: SGML <EMAIL> <SENDER> <PERSON> <FIRSTNAME>GEEKS FOR GEEKS</FIRSTNAME> </PERSON> </SENDER> <BODY> <p>A Computer Science Portal For Geeks</p> </BODY></EMAIL> Output: simple Paragraph Example 2: SGML <EMAIL> <RECEIVER> <PERSON> <FIRSTNAME>Krishna</FIRSTNAME> </PERSON> </RECEIVER> <BODY> <p>It is a name of the person.</p> </BODY></EMAIL> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n20 Aug, 2021" }, { "code": null, "e": 26477, "s": 26139, "text": "In this article, we are going to learn about SGML.SGML stands for Standard generalized markup language is a Standard generalized markup language that makes use of a superset of extensively used markup languages like HTML and XML. It is used for marking up files and has the gain of now no longer be depending on a particular application." }, { "code": null, "e": 26845, "s": 26477, "text": "It is basically derived from GML (Generalized Markup Language), which allowed users to work on standardized formatting styles for electronic documents. It was developed and standardized by the International Organization for Standards (ISO) in 1986. SGML specifies the rules for tagging elements. These tags can then be interpreted to layout factors in specific ways." }, { "code": null, "e": 27106, "s": 26845, "text": "It is used extensively to manipulate massive files which are a concern with common revisions and want to be published in one-of-a-kind formats due to the fact it’s far a massive and complicated system, it isn’t always but extensively used on private computers." }, { "code": null, "e": 27126, "s": 27106, "text": "Components of SGML:" }, { "code": null, "e": 27400, "s": 27126, "text": "SGML provides a way of describing the relationships between these entities, elements, and attributes, and tells the computer how it can recognize the component parts of a document and it is based on the concept of a document being composed of a series of entities (object)." }, { "code": null, "e": 27514, "s": 27400, "text": "It provides rules that allow the computer to recognize where the various elements of a text entity start and end." }, { "code": null, "e": 27646, "s": 27514, "text": "Document Type Definition (DTD) in SGML is used to describe each element of the document in a form that the computer can understand." }, { "code": null, "e": 27857, "s": 27646, "text": "SGML is the simplest medium to produce files that can be read by people and exchanged between machines and applications in a straightforward manner. It is easy to understand by the human as well as the machine." }, { "code": null, "e": 27876, "s": 27857, "text": "Structure of SGML:" }, { "code": null, "e": 27940, "s": 27876, "text": "<mainObject> \n <subObject> \n </subObject>\n</mainObject> " }, { "code": null, "e": 27973, "s": 27940, "text": "The extension of SGML files is: " }, { "code": null, "e": 27988, "s": 27973, "text": "File_Name.sgml" }, { "code": null, "e": 27996, "s": 27988, "text": "Syntax:" }, { "code": null, "e": 28043, "s": 27996, "text": "<NAME TYPE=\"user\">\n Geeks for Geeks\n</NAME> " }, { "code": null, "e": 28055, "s": 28043, "text": "Example 1: " }, { "code": null, "e": 28060, "s": 28055, "text": "SGML" }, { "code": "<EMAIL> <SENDER> <PERSON> <FIRSTNAME>GEEKS FOR GEEKS</FIRSTNAME> </PERSON> </SENDER> <BODY> <p>A Computer Science Portal For Geeks</p> </BODY></EMAIL>", "e": 28268, "s": 28060, "text": null }, { "code": null, "e": 28276, "s": 28268, "text": "Output:" }, { "code": null, "e": 28293, "s": 28276, "text": "simple Paragraph" }, { "code": null, "e": 28304, "s": 28293, "text": "Example 2:" }, { "code": null, "e": 28309, "s": 28304, "text": "SGML" }, { "code": "<EMAIL> <RECEIVER> <PERSON> <FIRSTNAME>Krishna</FIRSTNAME> </PERSON> </RECEIVER> <BODY> <p>It is a name of the person.</p> </BODY></EMAIL>", "e": 28507, "s": 28309, "text": null }, { "code": null, "e": 28515, "s": 28507, "text": "Output:" }, { "code": null, "e": 28652, "s": 28515, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28667, "s": 28652, "text": "HTML-Questions" }, { "code": null, "e": 28674, "s": 28667, "text": "Picked" }, { "code": null, "e": 28679, "s": 28674, "text": "HTML" }, { "code": null, "e": 28696, "s": 28679, "text": "Web Technologies" }, { "code": null, "e": 28701, "s": 28696, "text": "HTML" }, { "code": null, "e": 28799, "s": 28701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28823, "s": 28799, "text": "REST API (Introduction)" }, { "code": null, "e": 28864, "s": 28823, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28901, "s": 28864, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28930, "s": 28901, "text": "Form validation using jQuery" }, { "code": null, "e": 28950, "s": 28930, "text": "Angular File Upload" }, { "code": null, "e": 28990, "s": 28950, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29023, "s": 28990, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29068, "s": 29023, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29111, "s": 29068, "text": "How to fetch data from an API in ReactJS ?" } ]
ML | Boston Housing Kaggle Challenge with Linear Regression - GeeksforGeeks
04 Oct, 2021 Boston Housing Data: This dataset was taken from the StatLib library and is maintained by Carnegie Mellon University. This dataset concerns the housing prices in the housing city of Boston. The dataset provided has 506 instances with 13 features.The Description of the dataset is taken from Let’s make the Linear Regression Model, predicting housing pricesInputting Libraries and dataset. Python3 # Importing Librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # Importing Datafrom sklearn.datasets import load_bostonboston = load_boston() The shape of input Boston data and getting feature_names Python3 boston.data.shape Python3 boston.feature_names Converting data from nd-array to data frame and adding feature names to the data Python3 data = pd.DataFrame(boston.data)data.columns = boston.feature_names data.head(10) Adding ‘Price’ column to the dataset Python3 # Adding 'Price' (target) column to the databoston.target.shape Python3 data['Price'] = boston.targetdata.head() Description of Boston dataset Python3 data.describe() Info of Boston Dataset Python3 data.info() Getting input and output data and further splitting data to training and testing dataset. Python3 # Input Datax = boston.data # Output Datay = boston.target # splitting data to training and testing dataset. #from sklearn.cross_validation import train_test_split#the submodule cross_validation is renamed and reprecated to model_selectionfrom sklearn.model_selection import train_test_split xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size =0.2, random_state = 0) print("xtrain shape : ", xtrain.shape)print("xtest shape : ", xtest.shape)print("ytrain shape : ", ytrain.shape)print("ytest shape : ", ytest.shape) Applying Linear Regression Model to the dataset and predicting the prices. Python3 # Fitting Multi Linear regression model to training modelfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(xtrain, ytrain) # predicting the test set resultsy_pred = regressor.predict(xtest) Plotting Scatter graph to show the prediction results – ‘ytrue’ value vs ‘y_pred’ value Python3 # Plotting Scatter graph to show the prediction# results - 'ytrue' value vs 'y_pred' valueplt.scatter(ytest, y_pred, c = 'green')plt.xlabel("Price: in $1000's")plt.ylabel("Predicted value")plt.title("True value vs predicted value : Linear Regression")plt.show() Results of Linear Regression i.e. Mean Squared Error. Python3 # Results of Linear Regression.from sklearn.metrics import mean_squared_errormse = mean_squared_error(ytest, y_pred)print("Mean Square Error : ", mse) As per the result, our model is only 66.55% accurate. So, the prepared model is not very good for predicting housing prices. One can improve the prediction results using many other possible machine learning algorithms and techniques. nikhilecenitp tanwarsinghvaibhav Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial Copying Files to and from Docker Containers ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction Agents in Artificial Intelligence Activation functions in Neural Networks Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Underfitting and Overfitting
[ { "code": null, "e": 25881, "s": 25853, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26174, "s": 25881, "text": "Boston Housing Data: This dataset was taken from the StatLib library and is maintained by Carnegie Mellon University. This dataset concerns the housing prices in the housing city of Boston. The dataset provided has 506 instances with 13 features.The Description of the dataset is taken from " }, { "code": null, "e": 26274, "s": 26174, "text": "Let’s make the Linear Regression Model, predicting housing pricesInputting Libraries and dataset. " }, { "code": null, "e": 26282, "s": 26274, "text": "Python3" }, { "code": "# Importing Librariesimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # Importing Datafrom sklearn.datasets import load_bostonboston = load_boston()", "e": 26452, "s": 26282, "text": null }, { "code": null, "e": 26511, "s": 26452, "text": "The shape of input Boston data and getting feature_names " }, { "code": null, "e": 26519, "s": 26511, "text": "Python3" }, { "code": "boston.data.shape", "e": 26537, "s": 26519, "text": null }, { "code": null, "e": 26545, "s": 26537, "text": "Python3" }, { "code": "boston.feature_names", "e": 26566, "s": 26545, "text": null }, { "code": null, "e": 26650, "s": 26566, "text": " Converting data from nd-array to data frame and adding feature names to the data " }, { "code": null, "e": 26658, "s": 26650, "text": "Python3" }, { "code": "data = pd.DataFrame(boston.data)data.columns = boston.feature_names data.head(10)", "e": 26740, "s": 26658, "text": null }, { "code": null, "e": 26781, "s": 26740, "text": " Adding ‘Price’ column to the dataset " }, { "code": null, "e": 26789, "s": 26781, "text": "Python3" }, { "code": "# Adding 'Price' (target) column to the databoston.target.shape", "e": 26853, "s": 26789, "text": null }, { "code": null, "e": 26861, "s": 26853, "text": "Python3" }, { "code": "data['Price'] = boston.targetdata.head()", "e": 26902, "s": 26861, "text": null }, { "code": null, "e": 26935, "s": 26902, "text": " Description of Boston dataset " }, { "code": null, "e": 26943, "s": 26935, "text": "Python3" }, { "code": "data.describe()", "e": 26959, "s": 26943, "text": null }, { "code": null, "e": 26986, "s": 26959, "text": " Info of Boston Dataset " }, { "code": null, "e": 26994, "s": 26986, "text": "Python3" }, { "code": "data.info()", "e": 27006, "s": 26994, "text": null }, { "code": null, "e": 27100, "s": 27006, "text": " Getting input and output data and further splitting data to training and testing dataset. " }, { "code": null, "e": 27108, "s": 27100, "text": "Python3" }, { "code": "# Input Datax = boston.data # Output Datay = boston.target # splitting data to training and testing dataset. #from sklearn.cross_validation import train_test_split#the submodule cross_validation is renamed and reprecated to model_selectionfrom sklearn.model_selection import train_test_split xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size =0.2, random_state = 0) print(\"xtrain shape : \", xtrain.shape)print(\"xtest shape : \", xtest.shape)print(\"ytrain shape : \", ytrain.shape)print(\"ytest shape : \", ytest.shape)", "e": 27695, "s": 27108, "text": null }, { "code": null, "e": 27774, "s": 27695, "text": " Applying Linear Regression Model to the dataset and predicting the prices. " }, { "code": null, "e": 27782, "s": 27774, "text": "Python3" }, { "code": "# Fitting Multi Linear regression model to training modelfrom sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(xtrain, ytrain) # predicting the test set resultsy_pred = regressor.predict(xtest)", "e": 28016, "s": 27782, "text": null }, { "code": null, "e": 28106, "s": 28016, "text": "Plotting Scatter graph to show the prediction results – ‘ytrue’ value vs ‘y_pred’ value " }, { "code": null, "e": 28114, "s": 28106, "text": "Python3" }, { "code": "# Plotting Scatter graph to show the prediction# results - 'ytrue' value vs 'y_pred' valueplt.scatter(ytest, y_pred, c = 'green')plt.xlabel(\"Price: in $1000's\")plt.ylabel(\"Predicted value\")plt.title(\"True value vs predicted value : Linear Regression\")plt.show()", "e": 28376, "s": 28114, "text": null }, { "code": null, "e": 28432, "s": 28376, "text": "Results of Linear Regression i.e. Mean Squared Error. " }, { "code": null, "e": 28440, "s": 28432, "text": "Python3" }, { "code": "# Results of Linear Regression.from sklearn.metrics import mean_squared_errormse = mean_squared_error(ytest, y_pred)print(\"Mean Square Error : \", mse)", "e": 28591, "s": 28440, "text": null }, { "code": null, "e": 28827, "s": 28591, "text": "As per the result, our model is only 66.55% accurate. So, the prepared model is not very good for predicting housing prices. One can improve the prediction results using many other possible machine learning algorithms and techniques. " }, { "code": null, "e": 28841, "s": 28827, "text": "nikhilecenitp" }, { "code": null, "e": 28860, "s": 28841, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 28886, "s": 28860, "text": "Advanced Computer Subject" }, { "code": null, "e": 28903, "s": 28886, "text": "Machine Learning" }, { "code": null, "e": 28910, "s": 28903, "text": "Python" }, { "code": null, "e": 28927, "s": 28910, "text": "Machine Learning" }, { "code": null, "e": 29025, "s": 28927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29048, "s": 29025, "text": "System Design Tutorial" }, { "code": null, "e": 29092, "s": 29048, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 29126, "s": 29092, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 29157, "s": 29126, "text": "Clustering in Machine Learning" }, { "code": null, "e": 29183, "s": 29157, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29217, "s": 29183, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 29257, "s": 29217, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 29298, "s": 29257, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29331, "s": 29298, "text": "Support Vector Machine Algorithm" } ]
JavaScript String prototype Property - GeeksforGeeks
30 Jun, 2020 The prototype property allows to add new properties and methods to the existing JavaScript object types. There are two examples to describe the JavaScript String prototype property. Syntax: object.prototype.name = value Return Value: It returns a reference to the String.prototype object. Example 1: This example adds a property salary to the all objects. <!DOCTYPE HTML><html> <head> <title> JavaScript String prototype Property </title></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <p id="GFG_UP"></p> <button onclick="GFG_Fun();"> Click Here </button> <p id="GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function person(name, age) { this.name = name; this.age = age; } var p1 = new person("p1", 24); up.innerHTML = "Click on the button to add " + "a new property to all objects of" + " a given type.< br > " + JSON.stringify(p1); function GFG_Fun() { person.prototype.salary = 1000; down.innerHTML = p1.salary; } </script></body> </html> Output: Example 2: This example adds a method info to the all objects. <!DOCTYPE HTML><html> <head> <title> JavaScript String prototype Property </title></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <p id="GFG_UP"></p> <button onclick="GFG_Fun();"> Click Here </button> <p id="GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function person(name, age) { this.name = name; this.age = age; } var p1 = new person("p1", 22); up.innerHTML = "Click on the button to add" + " a new property to all objects " + "of a given type.< br > " + JSON.stringify(p1); function getData(name, age) { return "Information of person <br>Name - '" + name + "'<br>Age - " + age; } function GFG_Fun() { person.prototype.info = getData(p1.name, p1.age); down.innerHTML = p1.info; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n30 Jun, 2020" }, { "code": null, "e": 26803, "s": 26621, "text": "The prototype property allows to add new properties and methods to the existing JavaScript object types. There are two examples to describe the JavaScript String prototype property." }, { "code": null, "e": 26811, "s": 26803, "text": "Syntax:" }, { "code": null, "e": 26841, "s": 26811, "text": "object.prototype.name = value" }, { "code": null, "e": 26910, "s": 26841, "text": "Return Value: It returns a reference to the String.prototype object." }, { "code": null, "e": 26977, "s": 26910, "text": "Example 1: This example adds a property salary to the all objects." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript String prototype Property </title></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <p id=\"GFG_UP\"></p> <button onclick=\"GFG_Fun();\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function person(name, age) { this.name = name; this.age = age; } var p1 = new person(\"p1\", 24); up.innerHTML = \"Click on the button to add \" + \"a new property to all objects of\" + \" a given type.< br > \" + JSON.stringify(p1); function GFG_Fun() { person.prototype.salary = 1000; down.innerHTML = p1.salary; } </script></body> </html> ", "e": 27877, "s": 26977, "text": null }, { "code": null, "e": 27885, "s": 27877, "text": "Output:" }, { "code": null, "e": 27948, "s": 27885, "text": "Example 2: This example adds a method info to the all objects." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript String prototype Property </title></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <p id=\"GFG_UP\"></p> <button onclick=\"GFG_Fun();\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); function person(name, age) { this.name = name; this.age = age; } var p1 = new person(\"p1\", 22); up.innerHTML = \"Click on the button to add\" + \" a new property to all objects \" + \"of a given type.< br > \" + JSON.stringify(p1); function getData(name, age) { return \"Information of person <br>Name - '\" + name + \"'<br>Age - \" + age; } function GFG_Fun() { person.prototype.info = getData(p1.name, p1.age); down.innerHTML = p1.info; } </script></body> </html> ", "e": 29049, "s": 27948, "text": null }, { "code": null, "e": 29057, "s": 29049, "text": "Output:" }, { "code": null, "e": 29066, "s": 29057, "text": "CSS-Misc" }, { "code": null, "e": 29076, "s": 29066, "text": "HTML-Misc" }, { "code": null, "e": 29092, "s": 29076, "text": "JavaScript-Misc" }, { "code": null, "e": 29099, "s": 29092, "text": "Picked" }, { "code": null, "e": 29103, "s": 29099, "text": "CSS" }, { "code": null, "e": 29108, "s": 29103, "text": "HTML" }, { "code": null, "e": 29119, "s": 29108, "text": "JavaScript" }, { "code": null, "e": 29136, "s": 29119, "text": "Web Technologies" }, { "code": null, "e": 29163, "s": 29136, "text": "Web technologies Questions" }, { "code": null, "e": 29168, "s": 29163, "text": "HTML" }, { "code": null, "e": 29266, "s": 29168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29305, "s": 29266, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29342, "s": 29305, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29371, "s": 29342, "text": "Form validation using jQuery" }, { "code": null, "e": 29406, "s": 29371, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29448, "s": 29406, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29508, "s": 29448, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29561, "s": 29508, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29622, "s": 29561, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29646, "s": 29622, "text": "REST API (Introduction)" } ]
C# | Char.TryParse () Method - GeeksforGeeks
31 Jan, 2019 In C#, Char.TryParse() is Char class method which is used to convert the value from given string to its equivalent Unicode character. Its performance is better than Char.Parse() method. Syntax : public static bool TryParse(string str, out char result) Parameter: str: It is System.String type parameter which can contain single character or NULL. result: This is an uninitialized parameter which is used to store the Unicode character equivalent when the conversion succeeded, or an undefined value if the conversion failed. The type of this parameter is System.Char. Return Type: The method return True, if successfully converted the string, otherwise return False. So type of this method is System.Boolean. Note: When string is NULL or Length is equal to 1 then conversion failed.Example 1: Below is an program to demonstrates the use of Char.TryParse() Method . // C# program to illustrate the// Char.TryParse () Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; Char value; // Input Capital letter A result = Char.TryParse("A", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input Capital letter Z result = Char.TryParse("Z", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input Symbol letter result = Char.TryParse("$", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input number result = Char.TryParse("100", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input small letter z result = Char.TryParse("z", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); }} True A True Z True $ False True z Example 2: Below is an program to demonstrates the use Char.TryParse() method where the input is not a single character and start with a symbol. // C# program to illustrate the// Char.TryParse () Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; Char value; // Input is String return false result = Char.TryParse("GeeksforGeeks", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input letter start with symbol < result = Char.TryParse("<N", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); }} False False CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Lambda Expressions in C#
[ { "code": null, "e": 25657, "s": 25629, "text": "\n31 Jan, 2019" }, { "code": null, "e": 25843, "s": 25657, "text": "In C#, Char.TryParse() is Char class method which is used to convert the value from given string to its equivalent Unicode character. Its performance is better than Char.Parse() method." }, { "code": null, "e": 25852, "s": 25843, "text": "Syntax :" }, { "code": null, "e": 25910, "s": 25852, "text": "public static bool TryParse(string str, out char result)\n" }, { "code": null, "e": 25921, "s": 25910, "text": "Parameter:" }, { "code": null, "e": 26005, "s": 25921, "text": "str: It is System.String type parameter which can contain single character or NULL." }, { "code": null, "e": 26226, "s": 26005, "text": "result: This is an uninitialized parameter which is used to store the Unicode character equivalent when the conversion succeeded, or an undefined value if the conversion failed. The type of this parameter is System.Char." }, { "code": null, "e": 26367, "s": 26226, "text": "Return Type: The method return True, if successfully converted the string, otherwise return False. So type of this method is System.Boolean." }, { "code": null, "e": 26523, "s": 26367, "text": "Note: When string is NULL or Length is equal to 1 then conversion failed.Example 1: Below is an program to demonstrates the use of Char.TryParse() Method ." }, { "code": "// C# program to illustrate the// Char.TryParse () Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; Char value; // Input Capital letter A result = Char.TryParse(\"A\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input Capital letter Z result = Char.TryParse(\"Z\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input Symbol letter result = Char.TryParse(\"$\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input number result = Char.TryParse(\"100\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input small letter z result = Char.TryParse(\"z\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); }}", "e": 27731, "s": 26523, "text": null }, { "code": null, "e": 27767, "s": 27731, "text": "True\nA\nTrue\nZ\nTrue\n$\nFalse\n\nTrue\nz\n" }, { "code": null, "e": 27912, "s": 27767, "text": "Example 2: Below is an program to demonstrates the use Char.TryParse() method where the input is not a single character and start with a symbol." }, { "code": "// C# program to illustrate the// Char.TryParse () Methodusing System; class GFG { // Main Method static public void Main() { // Declaration of data type bool result; Char value; // Input is String return false result = Char.TryParse(\"GeeksforGeeks\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); // Input letter start with symbol < result = Char.TryParse(\"<N\", out value); // Display boolean type result Console.WriteLine(result); Console.WriteLine(value.ToString()); }}", "e": 28563, "s": 27912, "text": null }, { "code": null, "e": 28577, "s": 28563, "text": "False\n\nFalse\n" }, { "code": null, "e": 28591, "s": 28577, "text": "CSharp-method" }, { "code": null, "e": 28594, "s": 28591, "text": "C#" }, { "code": null, "e": 28692, "s": 28594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28715, "s": 28692, "text": "Extension Method in C#" }, { "code": null, "e": 28743, "s": 28715, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28760, "s": 28743, "text": "C# | Inheritance" }, { "code": null, "e": 28782, "s": 28760, "text": "Partial Classes in C#" }, { "code": null, "e": 28811, "s": 28782, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28851, "s": 28811, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28874, "s": 28851, "text": "Switch Statement in C#" }, { "code": null, "e": 28917, "s": 28874, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28957, "s": 28917, "text": "Convert String to Character Array in C#" } ]
Garbage Collection in Java - GeeksforGeeks
14 Feb, 2022 Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory. In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a certain point, sufficient memory may not be available to create new objects, and the entire program will terminate abnormally, causing OutOfMemoryErrors. But in Java, the programmer need not care for all those objects which are no longer in use. Garbage collector destroys these objects. The main objective of Garbage Collector is to free heap memory by destroying unreachable objects. The garbage collector is the best example of the Daemon thread as it is always running in the background. Java garbage collection is an automatic process. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused or unreferenced object is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage collection implementation lives in the JVM. Two types of garbage collection activity usually happen in Java. These are: Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young generation heap memory are removed.Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed. When compared to the young generation, garbage collection happens less frequently in the old generation. Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young generation heap memory are removed. Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed. When compared to the young generation, garbage collection happens less frequently in the old generation. 1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference to it. Also, note that objects which are part of the island of isolation are also unreachable. Integer i = new Integer(4); // the new Integer object is reachable via the reference in 'i' i = null; // the Integer object is no longer reachable. 2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage collection) if it is unreachable. After i = null, integer object 4 in the heap area is suitable for garbage collection in the above image. Even though the programmer is not responsible for destroying useless objects but it is highly recommended to make an object unreachable(thus eligible for GC) if it is no longer required. There are generally four ways to make an object eligible for garbage collection.Nullifying the reference variableRe-assigning the reference variableAn object created inside the methodIsland of Isolation Nullifying the reference variableRe-assigning the reference variableAn object created inside the methodIsland of Isolation Nullifying the reference variable Re-assigning the reference variable An object created inside the method Island of Isolation Once we make an object eligible for garbage collection, it may not destroy immediately by the garbage collector. Whenever JVM runs the Garbage Collector program, then only the object will be destroyed. But when JVM runs Garbage Collector, we can not expect. We can also request JVM to run Garbage Collector. There are two ways to do it : Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.There is no guarantee that any of the above two methods will run Garbage Collector.The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc() Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.There is no guarantee that any of the above two methods will run Garbage Collector.The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc() Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector. Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector. There is no guarantee that any of the above two methods will run Garbage Collector. The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc() Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object. finalize() method is present in Object class with the following prototype. protected void finalize() throws Throwable Based on our requirement, we can override finalize() method for performing our cleanup activities like closing connection from the database. The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM.Object class finalize() method has an empty implementation. Thus, it is recommended to override the finalize() method to dispose of system resources or perform other cleanups.The finalize() method is never invoked more than once for any object.If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of that object terminates. The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM. Object class finalize() method has an empty implementation. Thus, it is recommended to override the finalize() method to dispose of system resources or perform other cleanups. The finalize() method is never invoked more than once for any object. If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of that object terminates. The advantages of Garbage Collection in Java are: It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory. It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort. Let’s take a real-life example, where we use the concept of the garbage collector. Question: Suppose you go for the internship at GeeksForGeeks, and you were told to write a program to count the number of employees working in the company(excluding interns). To make this program, you have to use the concept of a garbage collector. This is the actual task you were given at the company: Write a program to create a class called Employee having the following data members. 1. An ID for storing unique id allocated to every employee. 2. Name of employee. 3. age of an employee. Also, provide the following methods: A parameterized constructor to initialize name and age. The ID should be initialized in this constructor.A method show() to display ID, name, and age.A method showNextId() to display the ID of the next employee. A parameterized constructor to initialize name and age. The ID should be initialized in this constructor. A method show() to display ID, name, and age. A method showNextId() to display the ID of the next employee. Now any beginner, who doesn’t know Garbage Collector in Java will code like this: Java // Java Program to count number// of employees working// in a company class Employee { private int ID; private String name; private int age; private static int nextId = 1; // it is made static because it // is keep common among all and // shared by all objects public Employee(String name, int age) { this.name = name; this.age = age; this.ID = nextId++; } public void show() { System.out.println("Id=" + ID + "\nName=" + name + "\nAge=" + age); } public void showNextId() { System.out.println("Next employee id will be=" + nextId); }} class UseEmployee { public static void main(String[] args) { Employee E = new Employee("GFG1", 56); Employee F = new Employee("GFG2", 45); Employee G = new Employee("GFG3", 25); E.show(); F.show(); G.show(); E.showNextId(); F.showNextId(); G.showNextId(); { // It is sub block to keep // all those interns. Employee X = new Employee("GFG4", 23); Employee Y = new Employee("GFG5", 21); X.show(); Y.show(); X.showNextId(); Y.showNextId(); } // After countering this brace, X and Y // will be removed.Therefore, // now it should show nextId as 4. // Output of this line E.showNextId(); // should be 4 but it will give 6 as output. }} Id=1 Name=GFG1 Age=56 Id=2 Name=GFG2 Age=45 Id=3 Name=GFG3 Age=25 Next employee id will be=4 Next employee id will be=4 Next employee id will be=4 Id=4 Name=GFG4 Age=23 Id=5 Name=GFG5 Age=21 Next employee id will be=6 Next employee id will be=6 Next employee id will be=6 Now to get the correct output: Now garbage collector(gc) will see 2 objects free. Now to decrement nextId,gc(garbage collector) will call method to finalize() only when we programmers have overridden it in our class. And as mentioned previously, we have to request gc(garbage collector), and for this, we have to write the following 3 steps before closing brace of sub-block. Set references to null(i.e X = Y = null;)Call, System.gc();Call, System.runFinalization(); Set references to null(i.e X = Y = null;) Call, System.gc(); Call, System.runFinalization(); Now the correct code for counting the number of employees(excluding interns) Java // Correct code to count number// of employees excluding interns. class Employee { private int ID; private String name; private int age; private static int nextId = 1; // it is made static because it // is keep common among all and // shared by all objects public Employee(String name, int age) { this.name = name; this.age = age; this.ID = nextId++; } public void show() { System.out.println("Id=" + ID + "\nName=" + name + "\nAge=" + age); } public void showNextId() { System.out.println("Next employee id will be=" + nextId); } protected void finalize() { --nextId; // In this case, // gc will call finalize() // for 2 times for 2 objects. }} public class UseEmployee { public static void main(String[] args) { Employee E = new Employee("GFG1", 56); Employee F = new Employee("GFG2", 45); Employee G = new Employee("GFG3", 25); E.show(); F.show(); G.show(); E.showNextId(); F.showNextId(); G.showNextId(); { // It is sub block to keep // all those interns. Employee X = new Employee("GFG4", 23); Employee Y = new Employee("GFG5", 21); X.show(); Y.show(); X.showNextId(); Y.showNextId(); X = Y = null; System.gc(); System.runFinalization(); } E.showNextId(); }} Output Id=1 Name=GFG1 Age=56 Id=2 Name=GFG2 Age=45 Id=3 Name=GFG3 Age=25 Next employee id will be=4 Next employee id will be=4 Next employee id will be=4 Id=4 Name=GFG4 Age=23 Id=5 Name=GFG5 Age=21 Next employee id will be=6 Next employee id will be=6 Next employee id will be=4 Related Articles: How to Make Object Eligible for Garbage Collection in Java? Island of Isolation in Java Output of Java programs | Set 10 (Garbage Collection) How to Find Max Memory, Free Memory, and Total Memory in Java? How JVM Works – JVM Architecture? This article is contributed by Chirag Agarwal and Gaurav Miglani. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above. AnshulVaidya nishkarshgandhi kingrajput450 java-garbage-collection Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Stream In Java HashMap in Java with Examples Reverse a string in Java Arrays.sort() in Java with examples Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24685, "s": 24657, "text": "\n14 Feb, 2022" }, { "code": null, "e": 25141, "s": 24685, "text": "Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory." }, { "code": null, "e": 25477, "s": 25141, "text": "In C/C++, a programmer is responsible for both the creation and destruction of objects. Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a certain point, sufficient memory may not be available to create new objects, and the entire program will terminate abnormally, causing OutOfMemoryErrors." }, { "code": null, "e": 25816, "s": 25477, "text": "But in Java, the programmer need not care for all those objects which are no longer in use. Garbage collector destroys these objects. The main objective of Garbage Collector is to free heap memory by destroying unreachable objects. The garbage collector is the best example of the Daemon thread as it is always running in the background. " }, { "code": null, "e": 26423, "s": 25816, "text": "Java garbage collection is an automatic process. Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object. An unused or unreferenced object is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage collection implementation lives in the JVM. " }, { "code": null, "e": 26499, "s": 26423, "text": "Two types of garbage collection activity usually happen in Java. These are:" }, { "code": null, "e": 26952, "s": 26499, "text": "Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young generation heap memory are removed.Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed. When compared to the young generation, garbage collection happens less frequently in the old generation." }, { "code": null, "e": 27095, "s": 26952, "text": "Minor or incremental Garbage Collection: It is said to have occurred when unreachable objects in the young generation heap memory are removed." }, { "code": null, "e": 27406, "s": 27095, "text": "Major or Full Garbage Collection: It is said to have occurred when the objects that survived the minor garbage collection are copied into the old generation or permanent generation heap memory are removed. When compared to the young generation, garbage collection happens less frequently in the old generation." }, { "code": null, "e": 27598, "s": 27406, "text": "1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference to it. Also, note that objects which are part of the island of isolation are also unreachable. " }, { "code": null, "e": 27749, "s": 27598, "text": "Integer i = new Integer(4);\n// the new Integer object is reachable via the reference in 'i' \ni = null;\n// the Integer object is no longer reachable. " }, { "code": null, "e": 27975, "s": 27749, "text": "2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage collection) if it is unreachable. After i = null, integer object 4 in the heap area is suitable for garbage collection in the above image." }, { "code": null, "e": 28162, "s": 27975, "text": "Even though the programmer is not responsible for destroying useless objects but it is highly recommended to make an object unreachable(thus eligible for GC) if it is no longer required." }, { "code": null, "e": 28365, "s": 28162, "text": "There are generally four ways to make an object eligible for garbage collection.Nullifying the reference variableRe-assigning the reference variableAn object created inside the methodIsland of Isolation" }, { "code": null, "e": 28488, "s": 28365, "text": "Nullifying the reference variableRe-assigning the reference variableAn object created inside the methodIsland of Isolation" }, { "code": null, "e": 28522, "s": 28488, "text": "Nullifying the reference variable" }, { "code": null, "e": 28558, "s": 28522, "text": "Re-assigning the reference variable" }, { "code": null, "e": 28594, "s": 28558, "text": "An object created inside the method" }, { "code": null, "e": 28614, "s": 28594, "text": "Island of Isolation" }, { "code": null, "e": 28872, "s": 28614, "text": "Once we make an object eligible for garbage collection, it may not destroy immediately by the garbage collector. Whenever JVM runs the Garbage Collector program, then only the object will be destroyed. But when JVM runs Garbage Collector, we can not expect." }, { "code": null, "e": 29448, "s": 28872, "text": "We can also request JVM to run Garbage Collector. There are two ways to do it : Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.There is no guarantee that any of the above two methods will run Garbage Collector.The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()" }, { "code": null, "e": 29944, "s": 29448, "text": "Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.There is no guarantee that any of the above two methods will run Garbage Collector.The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()" }, { "code": null, "e": 30055, "s": 29944, "text": "Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector." }, { "code": null, "e": 30272, "s": 30055, "text": "Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector." }, { "code": null, "e": 30356, "s": 30272, "text": "There is no guarantee that any of the above two methods will run Garbage Collector." }, { "code": null, "e": 30443, "s": 30356, "text": "The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()" }, { "code": null, "e": 30638, "s": 30443, "text": "Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object." }, { "code": null, "e": 30713, "s": 30638, "text": "finalize() method is present in Object class with the following prototype." }, { "code": null, "e": 30756, "s": 30713, "text": "protected void finalize() throws Throwable" }, { "code": null, "e": 30898, "s": 30756, "text": "Based on our requirement, we can override finalize() method for performing our cleanup activities like closing connection from the database. " }, { "code": null, "e": 31396, "s": 30898, "text": "The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM.Object class finalize() method has an empty implementation. Thus, it is recommended to override the finalize() method to dispose of system resources or perform other cleanups.The finalize() method is never invoked more than once for any object.If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of that object terminates." }, { "code": null, "e": 31516, "s": 31396, "text": "The finalize() method is called by Garbage Collector, not JVM. However, Garbage Collector is one of the modules of JVM." }, { "code": null, "e": 31692, "s": 31516, "text": "Object class finalize() method has an empty implementation. Thus, it is recommended to override the finalize() method to dispose of system resources or perform other cleanups." }, { "code": null, "e": 31762, "s": 31692, "text": "The finalize() method is never invoked more than once for any object." }, { "code": null, "e": 31897, "s": 31762, "text": "If an uncaught exception is thrown by the finalize() method, the exception is ignored, and the finalization of that object terminates." }, { "code": null, "e": 31947, "s": 31897, "text": "The advantages of Garbage Collection in Java are:" }, { "code": null, "e": 32059, "s": 31947, "text": "It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory." }, { "code": null, "e": 32156, "s": 32059, "text": "It is automatically done by the garbage collector(a part of JVM), so we don’t need extra effort." }, { "code": null, "e": 32239, "s": 32156, "text": "Let’s take a real-life example, where we use the concept of the garbage collector." }, { "code": null, "e": 32489, "s": 32239, "text": "Question: Suppose you go for the internship at GeeksForGeeks, and you were told to write a program to count the number of employees working in the company(excluding interns). To make this program, you have to use the concept of a garbage collector. " }, { "code": null, "e": 32544, "s": 32489, "text": "This is the actual task you were given at the company:" }, { "code": null, "e": 32630, "s": 32544, "text": "Write a program to create a class called Employee having the following data members. " }, { "code": null, "e": 32734, "s": 32630, "text": "1. An ID for storing unique id allocated to every employee. 2. Name of employee. 3. age of an employee." }, { "code": null, "e": 32771, "s": 32734, "text": "Also, provide the following methods:" }, { "code": null, "e": 32983, "s": 32771, "text": "A parameterized constructor to initialize name and age. The ID should be initialized in this constructor.A method show() to display ID, name, and age.A method showNextId() to display the ID of the next employee." }, { "code": null, "e": 33089, "s": 32983, "text": "A parameterized constructor to initialize name and age. The ID should be initialized in this constructor." }, { "code": null, "e": 33135, "s": 33089, "text": "A method show() to display ID, name, and age." }, { "code": null, "e": 33197, "s": 33135, "text": "A method showNextId() to display the ID of the next employee." }, { "code": null, "e": 33280, "s": 33197, "text": "Now any beginner, who doesn’t know Garbage Collector in Java will code like this: " }, { "code": null, "e": 33285, "s": 33280, "text": "Java" }, { "code": "// Java Program to count number// of employees working// in a company class Employee { private int ID; private String name; private int age; private static int nextId = 1; // it is made static because it // is keep common among all and // shared by all objects public Employee(String name, int age) { this.name = name; this.age = age; this.ID = nextId++; } public void show() { System.out.println(\"Id=\" + ID + \"\\nName=\" + name + \"\\nAge=\" + age); } public void showNextId() { System.out.println(\"Next employee id will be=\" + nextId); }} class UseEmployee { public static void main(String[] args) { Employee E = new Employee(\"GFG1\", 56); Employee F = new Employee(\"GFG2\", 45); Employee G = new Employee(\"GFG3\", 25); E.show(); F.show(); G.show(); E.showNextId(); F.showNextId(); G.showNextId(); { // It is sub block to keep // all those interns. Employee X = new Employee(\"GFG4\", 23); Employee Y = new Employee(\"GFG5\", 21); X.show(); Y.show(); X.showNextId(); Y.showNextId(); } // After countering this brace, X and Y // will be removed.Therefore, // now it should show nextId as 4. // Output of this line E.showNextId(); // should be 4 but it will give 6 as output. }}", "e": 34812, "s": 33285, "text": null }, { "code": null, "e": 35084, "s": 34812, "text": "Id=1\nName=GFG1\nAge=56\nId=2\nName=GFG2\nAge=45\nId=3\nName=GFG3\nAge=25\nNext employee id will be=4\nNext employee id will be=4\nNext employee id will be=4\nId=4\nName=GFG4\nAge=23\nId=5\nName=GFG5\nAge=21\nNext employee id will be=6\nNext employee id will be=6\nNext employee id will be=6" }, { "code": null, "e": 35462, "s": 35084, "text": "Now to get the correct output: Now garbage collector(gc) will see 2 objects free. Now to decrement nextId,gc(garbage collector) will call method to finalize() only when we programmers have overridden it in our class. And as mentioned previously, we have to request gc(garbage collector), and for this, we have to write the following 3 steps before closing brace of sub-block. " }, { "code": null, "e": 35553, "s": 35462, "text": "Set references to null(i.e X = Y = null;)Call, System.gc();Call, System.runFinalization();" }, { "code": null, "e": 35595, "s": 35553, "text": "Set references to null(i.e X = Y = null;)" }, { "code": null, "e": 35614, "s": 35595, "text": "Call, System.gc();" }, { "code": null, "e": 35646, "s": 35614, "text": "Call, System.runFinalization();" }, { "code": null, "e": 35725, "s": 35646, "text": "Now the correct code for counting the number of employees(excluding interns) " }, { "code": null, "e": 35730, "s": 35725, "text": "Java" }, { "code": "// Correct code to count number// of employees excluding interns. class Employee { private int ID; private String name; private int age; private static int nextId = 1; // it is made static because it // is keep common among all and // shared by all objects public Employee(String name, int age) { this.name = name; this.age = age; this.ID = nextId++; } public void show() { System.out.println(\"Id=\" + ID + \"\\nName=\" + name + \"\\nAge=\" + age); } public void showNextId() { System.out.println(\"Next employee id will be=\" + nextId); } protected void finalize() { --nextId; // In this case, // gc will call finalize() // for 2 times for 2 objects. }} public class UseEmployee { public static void main(String[] args) { Employee E = new Employee(\"GFG1\", 56); Employee F = new Employee(\"GFG2\", 45); Employee G = new Employee(\"GFG3\", 25); E.show(); F.show(); G.show(); E.showNextId(); F.showNextId(); G.showNextId(); { // It is sub block to keep // all those interns. Employee X = new Employee(\"GFG4\", 23); Employee Y = new Employee(\"GFG5\", 21); X.show(); Y.show(); X.showNextId(); Y.showNextId(); X = Y = null; System.gc(); System.runFinalization(); } E.showNextId(); }}", "e": 37287, "s": 35730, "text": null }, { "code": null, "e": 37294, "s": 37287, "text": "Output" }, { "code": null, "e": 37566, "s": 37294, "text": "Id=1\nName=GFG1\nAge=56\nId=2\nName=GFG2\nAge=45\nId=3\nName=GFG3\nAge=25\nNext employee id will be=4\nNext employee id will be=4\nNext employee id will be=4\nId=4\nName=GFG4\nAge=23\nId=5\nName=GFG5\nAge=21\nNext employee id will be=6\nNext employee id will be=6\nNext employee id will be=4" }, { "code": null, "e": 37586, "s": 37566, "text": "Related Articles: " }, { "code": null, "e": 37646, "s": 37586, "text": "How to Make Object Eligible for Garbage Collection in Java?" }, { "code": null, "e": 37674, "s": 37646, "text": "Island of Isolation in Java" }, { "code": null, "e": 37728, "s": 37674, "text": "Output of Java programs | Set 10 (Garbage Collection)" }, { "code": null, "e": 37791, "s": 37728, "text": "How to Find Max Memory, Free Memory, and Total Memory in Java?" }, { "code": null, "e": 37825, "s": 37791, "text": "How JVM Works – JVM Architecture?" }, { "code": null, "e": 38015, "s": 37825, "text": "This article is contributed by Chirag Agarwal and Gaurav Miglani. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above." }, { "code": null, "e": 38028, "s": 38015, "text": "AnshulVaidya" }, { "code": null, "e": 38044, "s": 38028, "text": "nishkarshgandhi" }, { "code": null, "e": 38058, "s": 38044, "text": "kingrajput450" }, { "code": null, "e": 38082, "s": 38058, "text": "java-garbage-collection" }, { "code": null, "e": 38087, "s": 38082, "text": "Java" }, { "code": null, "e": 38092, "s": 38087, "text": "Java" }, { "code": null, "e": 38190, "s": 38092, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38205, "s": 38190, "text": "Arrays in Java" }, { "code": null, "e": 38249, "s": 38205, "text": "Split() String method in Java with examples" }, { "code": null, "e": 38271, "s": 38249, "text": "For-each loop in Java" }, { "code": null, "e": 38322, "s": 38271, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 38337, "s": 38322, "text": "Stream In Java" }, { "code": null, "e": 38367, "s": 38337, "text": "HashMap in Java with Examples" }, { "code": null, "e": 38392, "s": 38367, "text": "Reverse a string in Java" }, { "code": null, "e": 38428, "s": 38392, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 38447, "s": 38428, "text": "Interfaces in Java" } ]
C++ Program For Sorting A Linked List Of 0s, 1s And 2s By Changing Links - GeeksforGeeks
11 Jan, 2022 Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 2->1->2->1->1->2->0->1->0 Output: 0->0->1->1->1->1->2->2->2 The sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2. Input: 2->1->0 Output: 0->1->2 The sorted Array is 0, 1, 2 Method 1: There is a solution discussed in below post that works by changing data of nodes. Sort a linked list of 0s, 1s and 2sThe above solution does not work when these values have associated data with them. For example, these three represent three colors and different types of objects associated with the colors and sort the objects (connected with a linked list) based on colors. Method 2: In this post, a new solution is discussed that works by changing links.Approach: Iterate through the linked list. Maintain 3 pointers named zero, one, and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD, and twoD that work as dummy headers of three lists. C++ // C++ Program to sort a linked list // 0s, 1s or 2s by changing links#include <bits/stdc++.h> // Link list node struct Node { int data; struct Node* next;}; Node* newNode(int data); // Sort a linked list of 0s, 1s // and 2s by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point // to beginning of three linked lists. // These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for // three lists and whole list. Node* zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; curr = curr->next; } else if (curr->data == 1) { one->next = curr; one = one->next; curr = curr->next; } else { two->next = curr; two = two->next; curr = curr->next; } } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes delete zeroD; delete oneD; delete twoD; return head;} // Function to create and return a nodeNode* newNode(int data){ // Allocating space Node* newNode = new Node; // Inserting the required data newNode->data = data; newNode->next = NULL;} // Function to print linked list void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("");} // Driver codeint main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf("Linked List Before Sorting"); printList(head); head = sortList(head); printf("Linked List After Sorting"); printList(head); return 0;} Output : Linked List Before Sorting 1 2 0 1 Linked List After Sorting 0 1 1 2 Complexity Analysis: Time Complexity: O(n) where n is a number of nodes in linked list. Only one traversal of the linked list is needed. Auxiliary Space: O(1). As no extra space is required. Please refer complete article on Sort a linked list of 0s, 1s and 2s by changing links for more details! Amazon Linked-List-Sorting MakeMyTrip Microsoft C++ Programs Linked List Sorting Amazon Microsoft MakeMyTrip Linked List Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Handling the Divide by Zero Exception in C++ Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 24606, "s": 24578, "text": "\n11 Jan, 2022" }, { "code": null, "e": 24662, "s": 24606, "text": "Given a linked list of 0s, 1s and 2s, sort it.Examples:" }, { "code": null, "e": 24836, "s": 24662, "text": "Input: 2->1->2->1->1->2->0->1->0\nOutput: 0->0->1->1->1->1->2->2->2\nThe sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2.\n\nInput: 2->1->0\nOutput: 0->1->2\nThe sorted Array is 0, 1, 2" }, { "code": null, "e": 25221, "s": 24836, "text": "Method 1: There is a solution discussed in below post that works by changing data of nodes. Sort a linked list of 0s, 1s and 2sThe above solution does not work when these values have associated data with them. For example, these three represent three colors and different types of objects associated with the colors and sort the objects (connected with a linked list) based on colors." }, { "code": null, "e": 25707, "s": 25221, "text": "Method 2: In this post, a new solution is discussed that works by changing links.Approach: Iterate through the linked list. Maintain 3 pointers named zero, one, and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD, and twoD that work as dummy headers of three lists." }, { "code": null, "e": 25711, "s": 25707, "text": "C++" }, { "code": "// C++ Program to sort a linked list // 0s, 1s or 2s by changing links#include <bits/stdc++.h> // Link list node struct Node { int data; struct Node* next;}; Node* newNode(int data); // Sort a linked list of 0s, 1s // and 2s by changing pointers.Node* sortList(Node* head){ if (!head || !(head->next)) return head; // Create three dummy nodes to point // to beginning of three linked lists. // These dummy nodes are created to // avoid many null checks. Node* zeroD = newNode(0); Node* oneD = newNode(0); Node* twoD = newNode(0); // Initialize current pointers for // three lists and whole list. Node* zero = zeroD, *one = oneD, *two = twoD; // Traverse list Node* curr = head; while (curr) { if (curr->data == 0) { zero->next = curr; zero = zero->next; curr = curr->next; } else if (curr->data == 1) { one->next = curr; one = one->next; curr = curr->next; } else { two->next = curr; two = two->next; curr = curr->next; } } // Attach three lists zero->next = (oneD->next) ? (oneD->next) : (twoD->next); one->next = twoD->next; two->next = NULL; // Updated head head = zeroD->next; // Delete dummy nodes delete zeroD; delete oneD; delete twoD; return head;} // Function to create and return a nodeNode* newNode(int data){ // Allocating space Node* newNode = new Node; // Inserting the required data newNode->data = data; newNode->next = NULL;} // Function to print linked list void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"\");} // Driver codeint main(void){ // Creating the list 1->2->4->5 Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(0); head->next->next->next = newNode(1); printf(\"Linked List Before Sorting\"); printList(head); head = sortList(head); printf(\"Linked List After Sorting\"); printList(head); return 0;}", "e": 27922, "s": 25711, "text": null }, { "code": null, "e": 27932, "s": 27922, "text": "Output : " }, { "code": null, "e": 28011, "s": 27932, "text": "Linked List Before Sorting\n1 2 0 1 \nLinked List After Sorting\n0 1 1 2 " }, { "code": null, "e": 28033, "s": 28011, "text": "Complexity Analysis: " }, { "code": null, "e": 28149, "s": 28033, "text": "Time Complexity: O(n) where n is a number of nodes in linked list. Only one traversal of the linked list is needed." }, { "code": null, "e": 28203, "s": 28149, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 28308, "s": 28203, "text": "Please refer complete article on Sort a linked list of 0s, 1s and 2s by changing links for more details!" }, { "code": null, "e": 28315, "s": 28308, "text": "Amazon" }, { "code": null, "e": 28335, "s": 28315, "text": "Linked-List-Sorting" }, { "code": null, "e": 28346, "s": 28335, "text": "MakeMyTrip" }, { "code": null, "e": 28356, "s": 28346, "text": "Microsoft" }, { "code": null, "e": 28369, "s": 28356, "text": "C++ Programs" }, { "code": null, "e": 28381, "s": 28369, "text": "Linked List" }, { "code": null, "e": 28389, "s": 28381, "text": "Sorting" }, { "code": null, "e": 28396, "s": 28389, "text": "Amazon" }, { "code": null, "e": 28406, "s": 28396, "text": "Microsoft" }, { "code": null, "e": 28417, "s": 28406, "text": "MakeMyTrip" }, { "code": null, "e": 28429, "s": 28417, "text": "Linked List" }, { "code": null, "e": 28437, "s": 28429, "text": "Sorting" }, { "code": null, "e": 28535, "s": 28437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28544, "s": 28535, "text": "Comments" }, { "code": null, "e": 28557, "s": 28544, "text": "Old Comments" }, { "code": null, "e": 28598, "s": 28557, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 28657, "s": 28598, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 28678, "s": 28657, "text": "Const keyword in C++" }, { "code": null, "e": 28690, "s": 28678, "text": "cout in C++" }, { "code": null, "e": 28735, "s": 28690, "text": "Handling the Divide by Zero Exception in C++" }, { "code": null, "e": 28770, "s": 28735, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 28809, "s": 28770, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 28831, "s": 28809, "text": "Reverse a linked list" }, { "code": null, "e": 28879, "s": 28831, "text": "Stack Data Structure (Introduction and Program)" } ]
How to Reverse keys and values in Scala Map
13 Aug, 2019 In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-comprehension. Keys should be unique for reverse these values otherwise we can lose some content.Syntax: val reverseMap = for ((k,v) <- map) yield (v, k) Below is the example to reverse keys and values in Scala Map. Example #1: // Scala program to reverse keys and values // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // reversing key:value pairs val reverse = for ((k, v) <- m1) yield (v, k) // Displays output println(reverse) } } Output: Map(geeks -> 3, for -> 4, cs -> 2) Example #2: // Scala program to reverse keys and values // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // Applying keySet method val reverse = for ((k, v) <- mapIm) yield (v, k) // Displays output println(reverse) } } Output: Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie) Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2019" }, { "code": null, "e": 428, "s": 28, "text": "In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-comprehension. Keys should be unique for reverse these values otherwise we can lose some content.Syntax:" }, { "code": null, "e": 477, "s": 428, "text": "val reverseMap = for ((k,v) <- map) yield (v, k)" }, { "code": null, "e": 539, "s": 477, "text": "Below is the example to reverse keys and values in Scala Map." }, { "code": null, "e": 551, "s": 539, "text": "Example #1:" }, { "code": "// Scala program to reverse keys and values // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // reversing key:value pairs val reverse = for ((k, v) <- m1) yield (v, k) // Displays output println(reverse) } } ", "e": 947, "s": 551, "text": null }, { "code": null, "e": 955, "s": 947, "text": "Output:" }, { "code": null, "e": 991, "s": 955, "text": "Map(geeks -> 3, for -> 4, cs -> 2)\n" }, { "code": null, "e": 1003, "s": 991, "text": "Example #2:" }, { "code": "// Scala program to reverse keys and values // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // Applying keySet method val reverse = for ((k, v) <- mapIm) yield (v, k) // Displays output println(reverse) } } ", "e": 1461, "s": 1003, "text": null }, { "code": null, "e": 1469, "s": 1461, "text": "Output:" }, { "code": null, "e": 1516, "s": 1469, "text": "Map(30 -> Ajay, 20 -> Bhavesh, 50 -> Charlie)\n" }, { "code": null, "e": 1522, "s": 1516, "text": "Scala" }, { "code": null, "e": 1532, "s": 1522, "text": "Scala-Map" }, { "code": null, "e": 1545, "s": 1532, "text": "Scala-Method" }, { "code": null, "e": 1551, "s": 1545, "text": "Scala" } ]
Python DateTime – strptime() Function
06 Sep, 2021 strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object. Syntax: datetime.strptime(time_data, format_data) Parameter: time_data is the time present in string format format_data is the data present in datetime format which is converted from time_data using this function. This function takes two arguments, a string in which some time is given and a format code, to change the string into, the string is changed to the DateTime object as per the list of codes given below. Format codes Example 1: Python program to read datetime and get all time data using strptime. Here we are going to take time data in the string format and going to extract hours, minutes, seconds, and milliseconds Python3 # import datetime module from datetimefrom datetime import datetime # consider the time stamp in string format# DD/MM/YY H:M:S.microstime_data = "25/05/99 02:35:5.523" # format the string in the given format :# day/month/year hours/minutes/seconds-micro# secondsformat_data = "%d/%m/%y %H:%M:%S.%f" # Using strptime with datetime we will format# string into datetimedate = datetime.strptime(time_data, format_data) # display milli secondprint(date.microsecond) # display hourprint(date.hour) # display minuteprint(date.minute) # display secondprint(date.second) # display dateprint(date) Output: 523000 2 35 5 1999-05-25 02:35:05.523000 Example 2: Python code that uses strptime. Here we are going to take time data in the string format and going to extract the time stamp in “%d/%m/%y %H:%M:%S.%f” format. Python3 # import datetime module from datetimefrom datetime import datetime # consider the time stamps from a list in string# format DD/MM/YY H:M:S.microstime_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003", "27/05/99 07:35:5.523", "28/05/99 05:15:55.523"] # format the string in the given format : day/month/year # hours/minutes/seconds-micro secondsformat_data = "%d/%m/%y %H:%M:%S.%f" # Using strptime with datetime we will format string# into datetimefor i in time_data: print(datetime.strptime(i, format_data)) Output: 1999-05-25 02:35:08.023000 1999-05-26 12:45:00.003000 1999-05-27 07:35:05.523000 1999-05-28 05:15:55.523000 we can get the time that follows a structure with all dates by using strptime() itself. Syntax: time.strptime(Timestamp, ‘%d/%m/%y %H:%M:%S’) where Timestamp includes time and date Example: Python code to get time in structure: Python3 #import timeimport time # get data of 4 th april 2021 at time 9 pmprint(time.strptime('04/04/21 09:31:22', '%d/%m/%y %H:%M:%S')) # get data of 5 th april 2021 at time 9 pmprint(time.strptime('05/04/21 09:00:42', '%d/%m/%y %H:%M:%S')) # get data of 6 th april 2021 at time 9 pmprint(time.strptime('06/04/21 09:11:42', '%d/%m/%y %H:%M:%S')) # get data of 7 th april 2021 at time 9 pmprint(time.strptime('07/04/21 09:41:12', '%d/%m/%y %H:%M:%S')) Output: time.struct_time(tm_year=2021, tm_mon=4, tm_mday=4, tm_hour=9, tm_min=31, tm_sec=22, tm_wday=6, tm_yday=94, tm_isdst=-1) time.struct_time(tm_year=2021, tm_mon=4, tm_mday=5, tm_hour=9, tm_min=0, tm_sec=42, tm_wday=0, tm_yday=95, tm_isdst=-1) time.struct_time(tm_year=2021, tm_mon=4, tm_mday=6, tm_hour=9, tm_min=11, tm_sec=42, tm_wday=1, tm_yday=96, tm_isdst=-1) time.struct_time(tm_year=2021, tm_mon=4, tm_mday=7, tm_hour=9, tm_min=41, tm_sec=12, tm_wday=2, tm_yday=97, tm_isdst=-1) It is also possible to get the string datetime in yyyy-mm-dd datetime format. yyyy-mm-dd stands for year-month-day. We can convert string format to DateTime by using the strptime() function. We will use the ‘%Y/%m/%d’ format to get the string to datetime. Syntax: datetime.datetime.strptime(input,format) Parameter: input is the string datetime format is the format – ‘yyyy-mm-dd’ datetime is the module For this first, the module is imported and the input DateTime string is given. Now use strptime to get the required format and get the date from DateTime using date() function Example 1: Python program to convert string datetime format to datetime Python3 # import the datetime moduleimport datetime # datetime in string format for may 25 1999input = '2021/05/25' # formatformat = '%Y/%m/%d' # convert from string format to datetime formatdatetime = datetime.datetime.strptime(input, format) # get the date from the datetime using date()# functionprint(datetime.date()) Output: 2021-05-25 Example 2: Convert list of string datetime to datetime Python3 # import the datetime moduleimport datetime # datetime in string format for list of datesinput = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4'] # formatformat = '%Y/%m/%d'for i in input: # convert from string format to datetime format # and get the date print(datetime.datetime.strptime(i, format).date()) Output: 2021-05-25 2020-05-25 2019-02-15 1999-02-04 We can also display DateTime in “%d/%m/%Y %H:%M:%S” Format. For this, we are going to get the data in date-month-year hours:minutes;seconds format. So we have to take input datetime string and get this format Syntax: datetime.strptime(input_date, “%d/%m/%Y %H:%M:%S”) Parameter: datetime is the module input_date is the string datetime format strptime is used to convert input_date string into datetime Example 3: Python program to get the string datetime into “%d/%m/%Y %H:%M:%S” Format Python3 #import datetimefrom datetime import datetime # consider the datetime string in dd/mm/yyyy# hh:mm:ss formatdate = "25/05/2021 02:35:15" # convert string datetime to dd/mm/yyyy hh:mm:ss# formatdatetime_date = datetime.strptime(date, "%d/%m/%Y %H:%M:%S")print(datetime_date) Output: 2021-05-25 02:35:15 rajeev0719singh Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2021" }, { "code": null, "e": 165, "s": 28, "text": "strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object." }, { "code": null, "e": 215, "s": 165, "text": "Syntax: datetime.strptime(time_data, format_data)" }, { "code": null, "e": 226, "s": 215, "text": "Parameter:" }, { "code": null, "e": 273, "s": 226, "text": "time_data is the time present in string format" }, { "code": null, "e": 379, "s": 273, "text": "format_data is the data present in datetime format which is converted from time_data using this function." }, { "code": null, "e": 580, "s": 379, "text": "This function takes two arguments, a string in which some time is given and a format code, to change the string into, the string is changed to the DateTime object as per the list of codes given below." }, { "code": null, "e": 593, "s": 580, "text": "Format codes" }, { "code": null, "e": 794, "s": 593, "text": "Example 1: Python program to read datetime and get all time data using strptime. Here we are going to take time data in the string format and going to extract hours, minutes, seconds, and milliseconds" }, { "code": null, "e": 802, "s": 794, "text": "Python3" }, { "code": "# import datetime module from datetimefrom datetime import datetime # consider the time stamp in string format# DD/MM/YY H:M:S.microstime_data = \"25/05/99 02:35:5.523\" # format the string in the given format :# day/month/year hours/minutes/seconds-micro# secondsformat_data = \"%d/%m/%y %H:%M:%S.%f\" # Using strptime with datetime we will format# string into datetimedate = datetime.strptime(time_data, format_data) # display milli secondprint(date.microsecond) # display hourprint(date.hour) # display minuteprint(date.minute) # display secondprint(date.second) # display dateprint(date)", "e": 1390, "s": 802, "text": null }, { "code": null, "e": 1398, "s": 1390, "text": "Output:" }, { "code": null, "e": 1405, "s": 1398, "text": "523000" }, { "code": null, "e": 1407, "s": 1405, "text": "2" }, { "code": null, "e": 1410, "s": 1407, "text": "35" }, { "code": null, "e": 1412, "s": 1410, "text": "5" }, { "code": null, "e": 1439, "s": 1412, "text": "1999-05-25 02:35:05.523000" }, { "code": null, "e": 1609, "s": 1439, "text": "Example 2: Python code that uses strptime. Here we are going to take time data in the string format and going to extract the time stamp in “%d/%m/%y %H:%M:%S.%f” format." }, { "code": null, "e": 1617, "s": 1609, "text": "Python3" }, { "code": "# import datetime module from datetimefrom datetime import datetime # consider the time stamps from a list in string# format DD/MM/YY H:M:S.microstime_data = [\"25/05/99 02:35:8.023\", \"26/05/99 12:45:0.003\", \"27/05/99 07:35:5.523\", \"28/05/99 05:15:55.523\"] # format the string in the given format : day/month/year # hours/minutes/seconds-micro secondsformat_data = \"%d/%m/%y %H:%M:%S.%f\" # Using strptime with datetime we will format string# into datetimefor i in time_data: print(datetime.strptime(i, format_data))", "e": 2148, "s": 1617, "text": null }, { "code": null, "e": 2156, "s": 2148, "text": "Output:" }, { "code": null, "e": 2183, "s": 2156, "text": "1999-05-25 02:35:08.023000" }, { "code": null, "e": 2210, "s": 2183, "text": "1999-05-26 12:45:00.003000" }, { "code": null, "e": 2237, "s": 2210, "text": "1999-05-27 07:35:05.523000" }, { "code": null, "e": 2264, "s": 2237, "text": "1999-05-28 05:15:55.523000" }, { "code": null, "e": 2353, "s": 2264, "text": "we can get the time that follows a structure with all dates by using strptime() itself. " }, { "code": null, "e": 2361, "s": 2353, "text": "Syntax:" }, { "code": null, "e": 2407, "s": 2361, "text": "time.strptime(Timestamp, ‘%d/%m/%y %H:%M:%S’)" }, { "code": null, "e": 2446, "s": 2407, "text": "where Timestamp includes time and date" }, { "code": null, "e": 2493, "s": 2446, "text": "Example: Python code to get time in structure:" }, { "code": null, "e": 2501, "s": 2493, "text": "Python3" }, { "code": "#import timeimport time # get data of 4 th april 2021 at time 9 pmprint(time.strptime('04/04/21 09:31:22', '%d/%m/%y %H:%M:%S')) # get data of 5 th april 2021 at time 9 pmprint(time.strptime('05/04/21 09:00:42', '%d/%m/%y %H:%M:%S')) # get data of 6 th april 2021 at time 9 pmprint(time.strptime('06/04/21 09:11:42', '%d/%m/%y %H:%M:%S')) # get data of 7 th april 2021 at time 9 pmprint(time.strptime('07/04/21 09:41:12', '%d/%m/%y %H:%M:%S'))", "e": 2949, "s": 2501, "text": null }, { "code": null, "e": 2957, "s": 2949, "text": "Output:" }, { "code": null, "e": 3078, "s": 2957, "text": "time.struct_time(tm_year=2021, tm_mon=4, tm_mday=4, tm_hour=9, tm_min=31, tm_sec=22, tm_wday=6, tm_yday=94, tm_isdst=-1)" }, { "code": null, "e": 3198, "s": 3078, "text": "time.struct_time(tm_year=2021, tm_mon=4, tm_mday=5, tm_hour=9, tm_min=0, tm_sec=42, tm_wday=0, tm_yday=95, tm_isdst=-1)" }, { "code": null, "e": 3319, "s": 3198, "text": "time.struct_time(tm_year=2021, tm_mon=4, tm_mday=6, tm_hour=9, tm_min=11, tm_sec=42, tm_wday=1, tm_yday=96, tm_isdst=-1)" }, { "code": null, "e": 3440, "s": 3319, "text": "time.struct_time(tm_year=2021, tm_mon=4, tm_mday=7, tm_hour=9, tm_min=41, tm_sec=12, tm_wday=2, tm_yday=97, tm_isdst=-1)" }, { "code": null, "e": 3698, "s": 3440, "text": "It is also possible to get the string datetime in yyyy-mm-dd datetime format. yyyy-mm-dd stands for year-month-day. We can convert string format to DateTime by using the strptime() function. We will use the ‘%Y/%m/%d’ format to get the string to datetime." }, { "code": null, "e": 3747, "s": 3698, "text": "Syntax: datetime.datetime.strptime(input,format)" }, { "code": null, "e": 3758, "s": 3747, "text": "Parameter:" }, { "code": null, "e": 3787, "s": 3758, "text": "input is the string datetime" }, { "code": null, "e": 3823, "s": 3787, "text": "format is the format – ‘yyyy-mm-dd’" }, { "code": null, "e": 3846, "s": 3823, "text": "datetime is the module" }, { "code": null, "e": 4022, "s": 3846, "text": "For this first, the module is imported and the input DateTime string is given. Now use strptime to get the required format and get the date from DateTime using date() function" }, { "code": null, "e": 4094, "s": 4022, "text": "Example 1: Python program to convert string datetime format to datetime" }, { "code": null, "e": 4102, "s": 4094, "text": "Python3" }, { "code": "# import the datetime moduleimport datetime # datetime in string format for may 25 1999input = '2021/05/25' # formatformat = '%Y/%m/%d' # convert from string format to datetime formatdatetime = datetime.datetime.strptime(input, format) # get the date from the datetime using date()# functionprint(datetime.date())", "e": 4416, "s": 4102, "text": null }, { "code": null, "e": 4424, "s": 4416, "text": "Output:" }, { "code": null, "e": 4435, "s": 4424, "text": "2021-05-25" }, { "code": null, "e": 4490, "s": 4435, "text": "Example 2: Convert list of string datetime to datetime" }, { "code": null, "e": 4498, "s": 4490, "text": "Python3" }, { "code": "# import the datetime moduleimport datetime # datetime in string format for list of datesinput = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4'] # formatformat = '%Y/%m/%d'for i in input: # convert from string format to datetime format # and get the date print(datetime.datetime.strptime(i, format).date())", "e": 4825, "s": 4498, "text": null }, { "code": null, "e": 4833, "s": 4825, "text": "Output:" }, { "code": null, "e": 4844, "s": 4833, "text": "2021-05-25" }, { "code": null, "e": 4855, "s": 4844, "text": "2020-05-25" }, { "code": null, "e": 4866, "s": 4855, "text": "2019-02-15" }, { "code": null, "e": 4877, "s": 4866, "text": "1999-02-04" }, { "code": null, "e": 5086, "s": 4877, "text": "We can also display DateTime in “%d/%m/%Y %H:%M:%S” Format. For this, we are going to get the data in date-month-year hours:minutes;seconds format. So we have to take input datetime string and get this format" }, { "code": null, "e": 5145, "s": 5086, "text": "Syntax: datetime.strptime(input_date, “%d/%m/%Y %H:%M:%S”)" }, { "code": null, "e": 5156, "s": 5145, "text": "Parameter:" }, { "code": null, "e": 5179, "s": 5156, "text": "datetime is the module" }, { "code": null, "e": 5220, "s": 5179, "text": "input_date is the string datetime format" }, { "code": null, "e": 5280, "s": 5220, "text": "strptime is used to convert input_date string into datetime" }, { "code": null, "e": 5365, "s": 5280, "text": "Example 3: Python program to get the string datetime into “%d/%m/%Y %H:%M:%S” Format" }, { "code": null, "e": 5373, "s": 5365, "text": "Python3" }, { "code": "#import datetimefrom datetime import datetime # consider the datetime string in dd/mm/yyyy# hh:mm:ss formatdate = \"25/05/2021 02:35:15\" # convert string datetime to dd/mm/yyyy hh:mm:ss# formatdatetime_date = datetime.strptime(date, \"%d/%m/%Y %H:%M:%S\")print(datetime_date)", "e": 5647, "s": 5373, "text": null }, { "code": null, "e": 5655, "s": 5647, "text": "Output:" }, { "code": null, "e": 5675, "s": 5655, "text": "2021-05-25 02:35:15" }, { "code": null, "e": 5691, "s": 5675, "text": "rajeev0719singh" }, { "code": null, "e": 5698, "s": 5691, "text": "Picked" }, { "code": null, "e": 5714, "s": 5698, "text": "Python-datetime" }, { "code": null, "e": 5721, "s": 5714, "text": "Python" }, { "code": null, "e": 5819, "s": 5721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5851, "s": 5819, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5878, "s": 5851, "text": "Python Classes and Objects" }, { "code": null, "e": 5909, "s": 5878, "text": "Python | os.path.join() method" }, { "code": null, "e": 5930, "s": 5909, "text": "Python OOPs Concepts" }, { "code": null, "e": 5953, "s": 5930, "text": "Introduction To PYTHON" }, { "code": null, "e": 6009, "s": 5953, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6051, "s": 6009, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6093, "s": 6051, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6132, "s": 6093, "text": "Python | Get unique values from a list" } ]
What is the use of curly brackets in the `var { ... } = ...` statements ?
15 Apr, 2020 Destructuring assignment allows us to assign the properties of an array or object to a bunch of variables that are sometimes very convenient and short. Consider the following illustration. Both of the below-mentioned methods are right and produce the same result. Without Destructuring:var array = [1, 20, 40]; var first = array[0] var second = array[1] var third = arr[2] var array = [1, 20, 40]; var first = array[0] var second = array[1] var third = arr[2] With Destructuringvar array = [1, 20, 40]; var [first, second, third] = array; var array = [1, 20, 40]; var [first, second, third] = array; Object Destructuring Destructuring can be done on JavaScript objects. On the left side of the assignment operator, there is a pattern of variables in which the properties of an object are to be stored. The variable’s name must be the same as defined in the object. Let’s have a look at this concept from the following example. Note: Curly brackets ‘{ }’ are used to destructure the JavaScript Object properties. Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> let example_object = { name: "Object", platform: "GeeksForGeeks", number: 100 }; let {name, platform, number} = example_object; console.log("Name: ", name); console.log("Platform: ", platform); console.log("Number: ", number); </script></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> let example_object = { name: "Object", platform: "GeeksForGeeks", number: 100 }; let {name, platform, number} = example_object; console.log("Name: ", name); console.log("Platform: ", platform); console.log("Number: ", number); </script></body> </html> Output: If we want the variables defined in the object should be assigned to the variables with other names then we can set it using a colon. Syntax:{sourceProperty : targetVariable} {sourceProperty : targetVariable} Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> let cuboid = { width: 100, height: 50, depth: 10 }; // width -> w // height -> h // depth -> d let {width:w, height:h, depth:d} = cuboid; console.log("Width: ", w); console.log("Height:", h); console.log("Depth: ", d); </script></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> let cuboid = { width: 100, height: 50, depth: 10 }; // width -> w // height -> h // depth -> d let {width:w, height:h, depth:d} = cuboid; console.log("Width: ", w); console.log("Height:", h); console.log("Depth: ", d); </script></body> </html> Output: Array Destructuring: The elements of the array can also be destructured in the same way. The destructuring assignment can be used to assign the array values to a bunch of different variables in JavaScript. Note: Square brackets ‘[ ]’ are used to destructure the array elements. Example:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> var arr = [1, 2, 3]; var [arr_1, arr_2, arr_3] = arr; console.log("First Element: ", arr_1); console.log("Second Element: ", arr_2); console.log("Third Element: ", arr_3); </script></body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>GeeksForGeeks</title></head> <body> <script> var arr = [1, 2, 3]; var [arr_1, arr_2, arr_3] = arr; console.log("First Element: ", arr_1); console.log("Second Element: ", arr_2); console.log("Third Element: ", arr_3); </script></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Apr, 2020" }, { "code": null, "e": 318, "s": 54, "text": "Destructuring assignment allows us to assign the properties of an array or object to a bunch of variables that are sometimes very convenient and short. Consider the following illustration. Both of the below-mentioned methods are right and produce the same result." }, { "code": null, "e": 429, "s": 318, "text": "Without Destructuring:var array = [1, 20, 40];\n\nvar first = array[0]\nvar second = array[1]\nvar third = arr[2]\n" }, { "code": null, "e": 518, "s": 429, "text": "var array = [1, 20, 40];\n\nvar first = array[0]\nvar second = array[1]\nvar third = arr[2]\n" }, { "code": null, "e": 599, "s": 518, "text": "With Destructuringvar array = [1, 20, 40];\n\nvar [first, second, third] = array;\n" }, { "code": null, "e": 662, "s": 599, "text": "var array = [1, 20, 40];\n\nvar [first, second, third] = array;\n" }, { "code": null, "e": 989, "s": 662, "text": "Object Destructuring Destructuring can be done on JavaScript objects. On the left side of the assignment operator, there is a pattern of variables in which the properties of an object are to be stored. The variable’s name must be the same as defined in the object. Let’s have a look at this concept from the following example." }, { "code": null, "e": 1074, "s": 989, "text": "Note: Curly brackets ‘{ }’ are used to destructure the JavaScript Object properties." }, { "code": null, "e": 1556, "s": 1074, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> let example_object = { name: \"Object\", platform: \"GeeksForGeeks\", number: 100 }; let {name, platform, number} = example_object; console.log(\"Name: \", name); console.log(\"Platform: \", platform); console.log(\"Number: \", number); </script></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> let example_object = { name: \"Object\", platform: \"GeeksForGeeks\", number: 100 }; let {name, platform, number} = example_object; console.log(\"Name: \", name); console.log(\"Platform: \", platform); console.log(\"Number: \", number); </script></body> </html>", "e": 2030, "s": 1556, "text": null }, { "code": null, "e": 2038, "s": 2030, "text": "Output:" }, { "code": null, "e": 2172, "s": 2038, "text": "If we want the variables defined in the object should be assigned to the variables with other names then we can set it using a colon." }, { "code": null, "e": 2213, "s": 2172, "text": "Syntax:{sourceProperty : targetVariable}" }, { "code": null, "e": 2247, "s": 2213, "text": "{sourceProperty : targetVariable}" }, { "code": null, "e": 2736, "s": 2247, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> let cuboid = { width: 100, height: 50, depth: 10 }; // width -> w // height -> h // depth -> d let {width:w, height:h, depth:d} = cuboid; console.log(\"Width: \", w); console.log(\"Height:\", h); console.log(\"Depth: \", d); </script></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> let cuboid = { width: 100, height: 50, depth: 10 }; // width -> w // height -> h // depth -> d let {width:w, height:h, depth:d} = cuboid; console.log(\"Width: \", w); console.log(\"Height:\", h); console.log(\"Depth: \", d); </script></body> </html>", "e": 3217, "s": 2736, "text": null }, { "code": null, "e": 3225, "s": 3217, "text": "Output:" }, { "code": null, "e": 3431, "s": 3225, "text": "Array Destructuring: The elements of the array can also be destructured in the same way. The destructuring assignment can be used to assign the array values to a bunch of different variables in JavaScript." }, { "code": null, "e": 3503, "s": 3431, "text": "Note: Square brackets ‘[ ]’ are used to destructure the array elements." }, { "code": null, "e": 3884, "s": 3503, "text": "Example:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> var arr = [1, 2, 3]; var [arr_1, arr_2, arr_3] = arr; console.log(\"First Element: \", arr_1); console.log(\"Second Element: \", arr_2); console.log(\"Third Element: \", arr_3); </script></body> </html>" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title>GeeksForGeeks</title></head> <body> <script> var arr = [1, 2, 3]; var [arr_1, arr_2, arr_3] = arr; console.log(\"First Element: \", arr_1); console.log(\"Second Element: \", arr_2); console.log(\"Third Element: \", arr_3); </script></body> </html>", "e": 4257, "s": 3884, "text": null }, { "code": null, "e": 4265, "s": 4257, "text": "Output:" }, { "code": null, "e": 4281, "s": 4265, "text": "JavaScript-Misc" }, { "code": null, "e": 4288, "s": 4281, "text": "Picked" }, { "code": null, "e": 4299, "s": 4288, "text": "JavaScript" }, { "code": null, "e": 4316, "s": 4299, "text": "Web Technologies" }, { "code": null, "e": 4343, "s": 4316, "text": "Web technologies Questions" } ]
Weak Entity Set in ER diagrams
05 Jul, 2021 An entity type should have a key attribute which uniquely identifies each entity in the entity set, but there exists some entity type for which key attribute can’t be defined. These are called Weak Entity type. The entity sets which do not have sufficient attributes to form a primary key are known as weak entity sets and the entity sets which have a primary key are known as strong entity sets. As the weak entities do not have any primary key, they cannot be identified on their own, so they depend on some other entity (known as owner entity). The weak entities have total participation constraint (existence dependency) in its identifying relationship with owner identity. Weak entity types have partial keys. Partial Keys are set of attributes with the help of which the tuples of the weak entities can be distinguished and identified. Note – Weak entity always has total participation but Strong entity may not have total participation. Weak entity is depend on strong entity to ensure the existence of weak entity. Like strong entity, weak entity does not have any primary key, It has partial discriminator key. Weak entity is represented by double rectangle. The relation between one strong and one weak entity is represented by double diamond. Weak entities are represented with double rectangular box in the ER Diagram and the identifying relationships are represented with double diamond. Partial Key attributes are represented with dotted lines. Example-1: In the below ER Diagram, ‘Payment’ is the weak entity. ‘Loan Payment’ is the identifying relationship and ‘Payment Number’ is the partial key. Primary Key of the Loan along with the partial key would be used to identify the records. Example-2: The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel. Example-3: The bank account of a particular bank has no existence if the bank doesn’t exist anymore. Example-4: A company may store the information of dependents (Parents, Children, Spouse) of an Employee. But the dependents don’t have existence without the employee. So Dependent will be weak entity type and Employee will be Identifying Entity type for Dependent. Other examples: Strong entity | Weak entity Order | Order Item Employee | Dependent Class | Section Host | Logins Note – Strong-Weak entity set always has parent-child relationship. singghakshay DBMS-ER model DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2021" }, { "code": null, "e": 266, "s": 54, "text": "An entity type should have a key attribute which uniquely identifies each entity in the entity set, but there exists some entity type for which key attribute can’t be defined. These are called Weak Entity type. " }, { "code": null, "e": 453, "s": 266, "text": "The entity sets which do not have sufficient attributes to form a primary key are known as weak entity sets and the entity sets which have a primary key are known as strong entity sets. " }, { "code": null, "e": 899, "s": 453, "text": "As the weak entities do not have any primary key, they cannot be identified on their own, so they depend on some other entity (known as owner entity). The weak entities have total participation constraint (existence dependency) in its identifying relationship with owner identity. Weak entity types have partial keys. Partial Keys are set of attributes with the help of which the tuples of the weak entities can be distinguished and identified. " }, { "code": null, "e": 1002, "s": 899, "text": "Note – Weak entity always has total participation but Strong entity may not have total participation. " }, { "code": null, "e": 1313, "s": 1002, "text": "Weak entity is depend on strong entity to ensure the existence of weak entity. Like strong entity, weak entity does not have any primary key, It has partial discriminator key. Weak entity is represented by double rectangle. The relation between one strong and one weak entity is represented by double diamond. " }, { "code": null, "e": 1521, "s": 1315, "text": "Weak entities are represented with double rectangular box in the ER Diagram and the identifying relationships are represented with double diamond. Partial Key attributes are represented with dotted lines. " }, { "code": null, "e": 1768, "s": 1523, "text": "Example-1: In the below ER Diagram, ‘Payment’ is the weak entity. ‘Loan Payment’ is the identifying relationship and ‘Payment Number’ is the partial key. Primary Key of the Loan along with the partial key would be used to identify the records. " }, { "code": null, "e": 1909, "s": 1770, "text": "Example-2: The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel. " }, { "code": null, "e": 2011, "s": 1909, "text": "Example-3: The bank account of a particular bank has no existence if the bank doesn’t exist anymore. " }, { "code": null, "e": 2277, "s": 2011, "text": "Example-4: A company may store the information of dependents (Parents, Children, Spouse) of an Employee. But the dependents don’t have existence without the employee. So Dependent will be weak entity type and Employee will be Identifying Entity type for Dependent. " }, { "code": null, "e": 2295, "s": 2277, "text": "Other examples: " }, { "code": null, "e": 2394, "s": 2295, "text": "Strong entity | Weak entity\nOrder | Order Item\nEmployee | Dependent\nClass | Section\nHost | Logins " }, { "code": null, "e": 2463, "s": 2394, "text": "Note – Strong-Weak entity set always has parent-child relationship. " }, { "code": null, "e": 2476, "s": 2463, "text": "singghakshay" }, { "code": null, "e": 2490, "s": 2476, "text": "DBMS-ER model" }, { "code": null, "e": 2495, "s": 2490, "text": "DBMS" }, { "code": null, "e": 2503, "s": 2495, "text": "GATE CS" }, { "code": null, "e": 2508, "s": 2503, "text": "DBMS" } ]
How to create a Scroll To Bottom button in ReactJS ?
30 Mar, 2021 You will see, there are lots of chat applications such as WhatsApp, Telegram, etc, that are using a useful feature like if you’re in the middle of a chat window, and you want to go to the bottom of the page then you can use this button to scroll down automatically like skip to the content. The following example covers how to create a Scroll To Bottom button in React JS using useState() hook. Prerequisite: Basic knowledge of npm & create-react-app command. Basic knowledge of styled-components. Basic Knowledge of useState() React hooks. Basic Setup: You will start a new project using create-react-app so open your terminal and type. npx create-react-app react-scroll-bottom Now go to your react-scroll-bottom folder by typing the given command in the terminal. cd react-scroll-bottom Required module: Install the dependencies required in this project by typing the given command in the terminal. npm install --save styled-components npm install --save react-icons Now create the components folder in src then go to the components folder and create two files ScrollButton.js and Styles.js. Project Structure: The file structure in the project will look like this. Example: In this example, we will design a webpage with Scroll To Bottom button, for that we will need to manipulate the App.js file and other created components file. We create a state with the first element visible as an initial state having a value of the true and the second element as function setVisible() for updating the state. Then a function is created by the name toggleVisible which sets the value of the state to false when we are scrolling down the page. Otherwise, the state value is set to true. Then a function is created by the name scrollToBottom in which we use the scrollTo method to scroll our page to the bottom. Now our state is used to show/hide the Scroll to bottom icon to the user. When the user clicks on this icon, the function scrollToBottom gets triggered as an onClick() event which scrolls our page smoothly to the bottom. You can also use ‘auto’ behavior in place of ‘smooth’. While scrolling down the page, the function toggleVisible also gets triggered as an event through window.addEventListener property and sets the state visible to false, which in turn hides our icon. When we return back to the top of the page by scrolling up ourselves, the state value updates to true and the icon again starts showing up. ScrollButton.js import React, {useState} from 'react'; import {FaArrowCircleDown} from 'react-icons/fa'; import { Button } from './Styles'; const ScrollButton = () =>{ const [visible, setVisible] = useState(true) const toggleVisible = () => { const scrolled = document.documentElement.scrollTop; if (scrolled > 0){ setVisible(false) } else if (scrolled <= 0){ setVisible(true) } }; const scrollToBottom = () =>{ window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'auto' /* you can also use 'auto' behaviour in place of 'smooth' */ }); }; window.addEventListener('scroll', toggleVisible); return ( <Button> <FaArrowCircleDown onClick={scrollToBottom} style={{display: visible ? 'inline' : 'none'}} /> </Button> ); } export default ScrollButton; Styles.js import styled from 'styled-components'; export const Header = styled.h1` text-align: center; left: 50%; color: green; `; export const Content = styled.div` overflowY: scroll; height: 2500px; `; export const Button = styled.div` position: fixed; width: 100%; left: 50%; height: 20px; font-size: 3rem; z-index: 1; cursor: pointer; color: green; ` App.js import { Fragment } from 'react'; import ScrollButton from './components/ScrollButton'; import { Content, Header } from './components/Styles'; function App() { return ( <Fragment> <Header>GeeksForGeeks Scroll To Bottom</Header> <ScrollButton /> <Content /> <Header>Thanks for visiting</Header> </Fragment> ); } export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Using default behavior (auto): See how it directly jumps to the bottom. Using smooth behavior: See how it goes smoothly to the bottom. Picked React-Questions Styled-components ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to do crud operations in ReactJS ? How to Use Bootstrap with React? How to install bootstrap in React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Mar, 2021" }, { "code": null, "e": 449, "s": 54, "text": "You will see, there are lots of chat applications such as WhatsApp, Telegram, etc, that are using a useful feature like if you’re in the middle of a chat window, and you want to go to the bottom of the page then you can use this button to scroll down automatically like skip to the content. The following example covers how to create a Scroll To Bottom button in React JS using useState() hook." }, { "code": null, "e": 463, "s": 449, "text": "Prerequisite:" }, { "code": null, "e": 514, "s": 463, "text": "Basic knowledge of npm & create-react-app command." }, { "code": null, "e": 552, "s": 514, "text": "Basic knowledge of styled-components." }, { "code": null, "e": 595, "s": 552, "text": "Basic Knowledge of useState() React hooks." }, { "code": null, "e": 692, "s": 595, "text": "Basic Setup: You will start a new project using create-react-app so open your terminal and type." }, { "code": null, "e": 733, "s": 692, "text": "npx create-react-app react-scroll-bottom" }, { "code": null, "e": 820, "s": 733, "text": "Now go to your react-scroll-bottom folder by typing the given command in the terminal." }, { "code": null, "e": 843, "s": 820, "text": "cd react-scroll-bottom" }, { "code": null, "e": 955, "s": 843, "text": "Required module: Install the dependencies required in this project by typing the given command in the terminal." }, { "code": null, "e": 1023, "s": 955, "text": "npm install --save styled-components\nnpm install --save react-icons" }, { "code": null, "e": 1148, "s": 1023, "text": "Now create the components folder in src then go to the components folder and create two files ScrollButton.js and Styles.js." }, { "code": null, "e": 1222, "s": 1148, "text": "Project Structure: The file structure in the project will look like this." }, { "code": null, "e": 1390, "s": 1222, "text": "Example: In this example, we will design a webpage with Scroll To Bottom button, for that we will need to manipulate the App.js file and other created components file." }, { "code": null, "e": 1734, "s": 1390, "text": "We create a state with the first element visible as an initial state having a value of the true and the second element as function setVisible() for updating the state. Then a function is created by the name toggleVisible which sets the value of the state to false when we are scrolling down the page. Otherwise, the state value is set to true." }, { "code": null, "e": 2473, "s": 1734, "text": "Then a function is created by the name scrollToBottom in which we use the scrollTo method to scroll our page to the bottom. Now our state is used to show/hide the Scroll to bottom icon to the user. When the user clicks on this icon, the function scrollToBottom gets triggered as an onClick() event which scrolls our page smoothly to the bottom. You can also use ‘auto’ behavior in place of ‘smooth’. While scrolling down the page, the function toggleVisible also gets triggered as an event through window.addEventListener property and sets the state visible to false, which in turn hides our icon. When we return back to the top of the page by scrolling up ourselves, the state value updates to true and the icon again starts showing up. " }, { "code": null, "e": 2489, "s": 2473, "text": "ScrollButton.js" }, { "code": "import React, {useState} from 'react'; import {FaArrowCircleDown} from 'react-icons/fa'; import { Button } from './Styles'; const ScrollButton = () =>{ const [visible, setVisible] = useState(true) const toggleVisible = () => { const scrolled = document.documentElement.scrollTop; if (scrolled > 0){ setVisible(false) } else if (scrolled <= 0){ setVisible(true) } }; const scrollToBottom = () =>{ window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'auto' /* you can also use 'auto' behaviour in place of 'smooth' */ }); }; window.addEventListener('scroll', toggleVisible); return ( <Button> <FaArrowCircleDown onClick={scrollToBottom} style={{display: visible ? 'inline' : 'none'}} /> </Button> ); } export default ScrollButton;", "e": 3367, "s": 2489, "text": null }, { "code": null, "e": 3377, "s": 3367, "text": "Styles.js" }, { "code": "import styled from 'styled-components'; export const Header = styled.h1` text-align: center; left: 50%; color: green; `; export const Content = styled.div` overflowY: scroll; height: 2500px; `; export const Button = styled.div` position: fixed; width: 100%; left: 50%; height: 20px; font-size: 3rem; z-index: 1; cursor: pointer; color: green; `", "e": 3773, "s": 3377, "text": null }, { "code": null, "e": 3780, "s": 3773, "text": "App.js" }, { "code": "import { Fragment } from 'react'; import ScrollButton from './components/ScrollButton'; import { Content, Header } from './components/Styles'; function App() { return ( <Fragment> <Header>GeeksForGeeks Scroll To Bottom</Header> <ScrollButton /> <Content /> <Header>Thanks for visiting</Header> </Fragment> ); } export default App;", "e": 4155, "s": 3780, "text": null }, { "code": null, "e": 4268, "s": 4155, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4278, "s": 4268, "text": "npm start" }, { "code": null, "e": 4377, "s": 4278, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 4449, "s": 4377, "text": "Using default behavior (auto): See how it directly jumps to the bottom." }, { "code": null, "e": 4512, "s": 4449, "text": "Using smooth behavior: See how it goes smoothly to the bottom." }, { "code": null, "e": 4519, "s": 4512, "text": "Picked" }, { "code": null, "e": 4535, "s": 4519, "text": "React-Questions" }, { "code": null, "e": 4553, "s": 4535, "text": "Styled-components" }, { "code": null, "e": 4561, "s": 4553, "text": "ReactJS" }, { "code": null, "e": 4578, "s": 4561, "text": "Web Technologies" }, { "code": null, "e": 4676, "s": 4578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4714, "s": 4676, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 4741, "s": 4714, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 4780, "s": 4741, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 4813, "s": 4780, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 4852, "s": 4813, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 4885, "s": 4852, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4947, "s": 4885, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5008, "s": 4947, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5058, "s": 5008, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
PyQtGraph – Scatter Plot Graph
18 Nov, 2021 In this article we will see how we can create a scatter plot graph using PyQtGraph module. PyQtGraph is a graphics and user interface Python library for functionalities commonly required in designing and science applications. Its provides fast, interactive graphics for displaying data (plots, video, etc.). A scatter plot uses dots to represent values for two different numeric variables. It is a type of plot that uses Cartesian coordinates to display values for typically two variables for a set of data. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. Scatter plots are used to observe relationships between variables. We can create a plot window and create scatter plot graph on it with the help of commands given below # creating a pyqtgraph plot window plt = pg.plot() # creating a scatter plot graphof size = 10 scatter = pg.ScatterPlotItem(size=10) In order to create a scatter plot graph in pyqtgraph, following steps needs to be followed: Import the pyqtgraph moduleimport other modules as well like numpy and pyqt5Create a main window classCreate scatter plot itemCreate random spots at random position using numpyAdd those spots to the scatter plot dataCreate a grid layoutAdd scatter plot and additional label to the layoutSet layout widget as the central widget Import the pyqtgraph module import other modules as well like numpy and pyqt5 Create a main window class Create scatter plot item Create random spots at random position using numpy Add those spots to the scatter plot data Create a grid layout Add scatter plot and additional label to the layout Set layout widget as the central widget Example: Python3 # importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks Scatter Plot") # making label do word wrap label.setWordWrap(True) # creating a plot window plot = pg.plot() # number of points n = 300 # creating a scatter plot item # of size = 10 # using brush to enlarge the of white color with transparency is 50% scatter = pg.ScatterPlotItem( size=10, brush=pg.mkBrush(255, 255, 255, 120)) # getting random position pos = np.random.normal(size=(2, n), scale=1e-5) # creating spots using the random position spots = [{'pos': pos[:, i], 'data': 1} for i in range(n)] + [{'pos': [0, 0], 'data': 1}] # adding points to the scatter plot scatter.addPoints(spots) # add item to plot window # adding scatter plot item to the plot window plot.addItem(scatter) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sweetyty Python-gui Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2021" }, { "code": null, "e": 712, "s": 28, "text": "In this article we will see how we can create a scatter plot graph using PyQtGraph module. PyQtGraph is a graphics and user interface Python library for functionalities commonly required in designing and science applications. Its provides fast, interactive graphics for displaying data (plots, video, etc.). A scatter plot uses dots to represent values for two different numeric variables. It is a type of plot that uses Cartesian coordinates to display values for typically two variables for a set of data. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. Scatter plots are used to observe relationships between variables." }, { "code": null, "e": 816, "s": 712, "text": "We can create a plot window and create scatter plot graph on it with the help of commands given below " }, { "code": null, "e": 950, "s": 816, "text": "# creating a pyqtgraph plot window\nplt = pg.plot()\n\n# creating a scatter plot graphof size = 10\nscatter = pg.ScatterPlotItem(size=10)" }, { "code": null, "e": 1042, "s": 950, "text": "In order to create a scatter plot graph in pyqtgraph, following steps needs to be followed:" }, { "code": null, "e": 1370, "s": 1042, "text": "Import the pyqtgraph moduleimport other modules as well like numpy and pyqt5Create a main window classCreate scatter plot itemCreate random spots at random position using numpyAdd those spots to the scatter plot dataCreate a grid layoutAdd scatter plot and additional label to the layoutSet layout widget as the central widget " }, { "code": null, "e": 1398, "s": 1370, "text": "Import the pyqtgraph module" }, { "code": null, "e": 1448, "s": 1398, "text": "import other modules as well like numpy and pyqt5" }, { "code": null, "e": 1475, "s": 1448, "text": "Create a main window class" }, { "code": null, "e": 1500, "s": 1475, "text": "Create scatter plot item" }, { "code": null, "e": 1551, "s": 1500, "text": "Create random spots at random position using numpy" }, { "code": null, "e": 1592, "s": 1551, "text": "Add those spots to the scatter plot data" }, { "code": null, "e": 1613, "s": 1592, "text": "Create a grid layout" }, { "code": null, "e": 1665, "s": 1613, "text": "Add scatter plot and additional label to the layout" }, { "code": null, "e": 1706, "s": 1665, "text": "Set layout widget as the central widget " }, { "code": null, "e": 1716, "s": 1706, "text": "Example: " }, { "code": null, "e": 1724, "s": 1716, "text": "Python3" }, { "code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import * class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel(\"Geeksforgeeks Scatter Plot\") # making label do word wrap label.setWordWrap(True) # creating a plot window plot = pg.plot() # number of points n = 300 # creating a scatter plot item # of size = 10 # using brush to enlarge the of white color with transparency is 50% scatter = pg.ScatterPlotItem( size=10, brush=pg.mkBrush(255, 255, 255, 120)) # getting random position pos = np.random.normal(size=(2, n), scale=1e-5) # creating spots using the random position spots = [{'pos': pos[:, i], 'data': 1} for i in range(n)] + [{'pos': [0, 0], 'data': 1}] # adding points to the scatter plot scatter.addPoints(spots) # add item to plot window # adding scatter plot item to the plot window plot.addItem(scatter) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setMinimumWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(plot, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 4024, "s": 1724, "text": null }, { "code": null, "e": 4035, "s": 4024, "text": "Output : " }, { "code": null, "e": 4046, "s": 4037, "text": "sweetyty" }, { "code": null, "e": 4057, "s": 4046, "text": "Python-gui" }, { "code": null, "e": 4074, "s": 4057, "text": "Python-PyQtGraph" }, { "code": null, "e": 4081, "s": 4074, "text": "Python" } ]
Matplotlib.pyplot.gray() in Python
21 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The gray() function in pyplot module of matplotlib library is used to set the colormap to “gray”. Syntax: matplotlib.pyplot.gray() Below examples illustrate the matplotlib.pyplot.gray() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 3 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat') plt.colorbar(tpc)plt.gray()plt.title('matplotlib.pyplot.gray() function\Example\n\n', fontweight ="bold") plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2 plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.gray()plt.title('matplotlib.pyplot.gray() function Example\n\n', fontweight ="bold") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 321, "s": 223, "text": "The gray() function in pyplot module of matplotlib library is used to set the colormap to “gray”." }, { "code": null, "e": 329, "s": 321, "text": "Syntax:" }, { "code": null, "e": 355, "s": 329, "text": "matplotlib.pyplot.gray()\n" }, { "code": null, "e": 441, "s": 355, "text": "Below examples illustrate the matplotlib.pyplot.gray() function in matplotlib.pyplot:" }, { "code": null, "e": 453, "s": 441, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 3 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat') plt.colorbar(tpc)plt.gray()plt.title('matplotlib.pyplot.gray() function\\Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 1281, "s": 453, "text": null }, { "code": null, "e": 1289, "s": 1281, "text": "Output:" }, { "code": null, "e": 1301, "s": 1289, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2 plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent)plt.gray()plt.title('matplotlib.pyplot.gray() function Example\\n\\n', fontweight =\"bold\") plt.show()", "e": 2072, "s": 1301, "text": null }, { "code": null, "e": 2080, "s": 2072, "text": "Output:" }, { "code": null, "e": 2098, "s": 2080, "text": "Python-matplotlib" }, { "code": null, "e": 2105, "s": 2098, "text": "Python" } ]
Python Program to Convert any Positive Real Number to Binary string
10 May, 2020 Given any Real Number greater than or equal to zero that is passed in as float, print binary representation of entered real number. Examples: Input: 123.5 Output: 1 1 1 1 0 1 1 . 1 Input: 0.25 Output: .01 Mathematical Logic along with steps done in programming: Any real number is divided into two parts: The integer part and the Fraction part. For both parts operations and logic are different to convert them to binary representation. Integer Part:Step 1: Divide Integer part by 2 and note its Remainder(it will be either 0 or 1).Step 2: Again divide integer part by 2(integer obtained from step 1 by dividing initial integer by 2) and note its Remainder.Repeat these steps until your integer does not becomes zero.Step 3: Now reverse the sequence of Remainders you noted at each step.and this is your binary representation of integer part.Programming steps:def intpartbinary(m): a=[] n=int(m) while n!=0: a.append(n%2) n=n//2 a.reverse() return aDefining a function intpartbinary() to convert integer part to binary representation. Define an Empty list taking integer part of an entered real number and divide it by 2 and store its remainder into an empty list each time while n==0, reverse the list and that will be the binary representation of integer part. Step 1: Divide Integer part by 2 and note its Remainder(it will be either 0 or 1).Step 2: Again divide integer part by 2(integer obtained from step 1 by dividing initial integer by 2) and note its Remainder.Repeat these steps until your integer does not becomes zero.Step 3: Now reverse the sequence of Remainders you noted at each step.and this is your binary representation of integer part. Programming steps: def intpartbinary(m): a=[] n=int(m) while n!=0: a.append(n%2) n=n//2 a.reverse() return a Defining a function intpartbinary() to convert integer part to binary representation. Define an Empty list taking integer part of an entered real number and divide it by 2 and store its remainder into an empty list each time while n==0, reverse the list and that will be the binary representation of integer part. Fractional Part:Step 1: Multiply fractional part by 2 and write its integer part only.Step 2: Subtract integer part from the number obtained in step 1(multiplying fraction part by 2) and again multiply fractional part by 2.Repeat these steps until the Fractional part does not become Zero. The sequence obtained is Binary representation of given fractional part.Programming Steps:def decimalpartbinary(m): a=[] n=m-int(m) while n!=0: x=2*n y=int(x) a.append(y) n=x-y return aDefining a function decimalpartbinary() to convert fractional part to binary. Again define an empty list, extracting fractional part from entered real number by subtracting integer part of entered real number from entered real number. Now multiply it by 2 and store only integer part of resulting number into the list and again taking fractional part and multiply by 2, store its integer part. Repeat this process until the fractional part does not become zero, and that will be the binary representation of the fractional part. Programming Steps: def decimalpartbinary(m): a=[] n=m-int(m) while n!=0: x=2*n y=int(x) a.append(y) n=x-y return a Defining a function decimalpartbinary() to convert fractional part to binary. Again define an empty list, extracting fractional part from entered real number by subtracting integer part of entered real number from entered real number. Now multiply it by 2 and store only integer part of resulting number into the list and again taking fractional part and multiply by 2, store its integer part. Repeat this process until the fractional part does not become zero, and that will be the binary representation of the fractional part. Now at last combining, all the binary conversion in given below format will be the binary representation of entered real number. Firstly write the reversed sequence of remainders and a dot(point) then write integer part sequence which we obtained by multiplying fraction part by 2 and extracting integer part only. def binarycode(m): a = intpartbinary(m) b = decimalpartbinary(m) c = [] for i in range(0, len(a)): c.append(a[i]) c.append('.') for j in range(0, len(b)): c.append(b[j]) print('Binary code of given function is\n') for k in range(0, len(c)): print(c[k], end=' ') For this, we will define a function named binarycode(). Define an empty list c=[], firstly store reversed list of remainder obtained by dividing integer part by 2 each time and then store a decimal in that list c, now store the list of integer part obtained by multiplying fraction part by 2 each time and storing only integer part. Now print list c. Finally, we will have our Binary Representation of Real Number into Binary Representation. Below is the implementation. # defining a function to convert # integer part to binarydef intpartbinary(m): a = [] n = int(m) while n != 0: a.append(n % 2) n = n//2 a.reverse() return a # defining a function to convert # fractional part to binarydef decimalpartbinary(m): a = [] n = m-int(m) while n != 0: x = 2 * n y = int(x) a.append(y) n = x-y return a# arranging all data into suitable formatdef binarycode(m): # arranging all data to our desired # format a = intpartbinary(m) b = decimalpartbinary(m) c =[] for i in range(0, len(a)): c.append(a[i]) c.append('.') for j in range(0, len(b)): c.append(b[j]) print('Binary code of given function is\n') for k in range(0, len(c)): print(c[k], end =' ') # Driver Codebinarycode(123.5) Output: Binary code of given function is 1 1 1 1 0 1 1 . 1 binary-representation Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 160, "s": 28, "text": "Given any Real Number greater than or equal to zero that is passed in as float, print binary representation of entered real number." }, { "code": null, "e": 170, "s": 160, "text": "Examples:" }, { "code": null, "e": 234, "s": 170, "text": "Input: 123.5\nOutput: 1 1 1 1 0 1 1 . 1\n\nInput: 0.25\nOutput: .01" }, { "code": null, "e": 291, "s": 234, "text": "Mathematical Logic along with steps done in programming:" }, { "code": null, "e": 466, "s": 291, "text": "Any real number is divided into two parts: The integer part and the Fraction part. For both parts operations and logic are different to convert them to binary representation." }, { "code": null, "e": 1331, "s": 466, "text": "Integer Part:Step 1: Divide Integer part by 2 and note its Remainder(it will be either 0 or 1).Step 2: Again divide integer part by 2(integer obtained from step 1 by dividing initial integer by 2) and note its Remainder.Repeat these steps until your integer does not becomes zero.Step 3: Now reverse the sequence of Remainders you noted at each step.and this is your binary representation of integer part.Programming steps:def intpartbinary(m):\n\n a=[]\n n=int(m)\n\n while n!=0:\n a.append(n%2)\n n=n//2\n a.reverse()\n\n return aDefining a function intpartbinary() to convert integer part to binary representation. Define an Empty list taking integer part of an entered real number and divide it by 2 and store its remainder into an empty list each time while n==0, reverse the list and that will be the binary representation of integer part." }, { "code": null, "e": 1724, "s": 1331, "text": "Step 1: Divide Integer part by 2 and note its Remainder(it will be either 0 or 1).Step 2: Again divide integer part by 2(integer obtained from step 1 by dividing initial integer by 2) and note its Remainder.Repeat these steps until your integer does not becomes zero.Step 3: Now reverse the sequence of Remainders you noted at each step.and this is your binary representation of integer part." }, { "code": null, "e": 1743, "s": 1724, "text": "Programming steps:" }, { "code": null, "e": 1872, "s": 1743, "text": "def intpartbinary(m):\n\n a=[]\n n=int(m)\n\n while n!=0:\n a.append(n%2)\n n=n//2\n a.reverse()\n\n return a" }, { "code": null, "e": 2186, "s": 1872, "text": "Defining a function intpartbinary() to convert integer part to binary representation. Define an Empty list taking integer part of an entered real number and divide it by 2 and store its remainder into an empty list each time while n==0, reverse the list and that will be the binary representation of integer part." }, { "code": null, "e": 3241, "s": 2186, "text": "Fractional Part:Step 1: Multiply fractional part by 2 and write its integer part only.Step 2: Subtract integer part from the number obtained in step 1(multiplying fraction part by 2) and again multiply fractional part by 2.Repeat these steps until the Fractional part does not become Zero. The sequence obtained is Binary representation of given fractional part.Programming Steps:def decimalpartbinary(m):\n\n a=[]\n n=m-int(m)\n\n while n!=0:\n x=2*n\n y=int(x)\n a.append(y)\n n=x-y\n\n return aDefining a function decimalpartbinary() to convert fractional part to binary. Again define an empty list, extracting fractional part from entered real number by subtracting integer part of entered real number from entered real number. Now multiply it by 2 and store only integer part of resulting number into the list and again taking fractional part and multiply by 2, store its integer part. Repeat this process until the fractional part does not become zero, and that will be the binary representation of the fractional part." }, { "code": null, "e": 3260, "s": 3241, "text": "Programming Steps:" }, { "code": null, "e": 3407, "s": 3260, "text": "def decimalpartbinary(m):\n\n a=[]\n n=m-int(m)\n\n while n!=0:\n x=2*n\n y=int(x)\n a.append(y)\n n=x-y\n\n return a" }, { "code": null, "e": 3936, "s": 3407, "text": "Defining a function decimalpartbinary() to convert fractional part to binary. Again define an empty list, extracting fractional part from entered real number by subtracting integer part of entered real number from entered real number. Now multiply it by 2 and store only integer part of resulting number into the list and again taking fractional part and multiply by 2, store its integer part. Repeat this process until the fractional part does not become zero, and that will be the binary representation of the fractional part." }, { "code": null, "e": 4251, "s": 3936, "text": "Now at last combining, all the binary conversion in given below format will be the binary representation of entered real number. Firstly write the reversed sequence of remainders and a dot(point) then write integer part sequence which we obtained by multiplying fraction part by 2 and extracting integer part only." }, { "code": null, "e": 4575, "s": 4251, "text": "def binarycode(m):\n\n a = intpartbinary(m)\n b = decimalpartbinary(m)\n c = []\n\n for i in range(0, len(a)):\n c.append(a[i])\n\n c.append('.')\n\n for j in range(0, len(b)):\n c.append(b[j])\n\n print('Binary code of given function is\\n')\n\n for k in range(0, len(c)):\n print(c[k], end=' ')" }, { "code": null, "e": 5017, "s": 4575, "text": "For this, we will define a function named binarycode(). Define an empty list c=[], firstly store reversed list of remainder obtained by dividing integer part by 2 each time and then store a decimal in that list c, now store the list of integer part obtained by multiplying fraction part by 2 each time and storing only integer part. Now print list c. Finally, we will have our Binary Representation of Real Number into Binary Representation." }, { "code": null, "e": 5046, "s": 5017, "text": "Below is the implementation." }, { "code": "# defining a function to convert # integer part to binarydef intpartbinary(m): a = [] n = int(m) while n != 0: a.append(n % 2) n = n//2 a.reverse() return a # defining a function to convert # fractional part to binarydef decimalpartbinary(m): a = [] n = m-int(m) while n != 0: x = 2 * n y = int(x) a.append(y) n = x-y return a# arranging all data into suitable formatdef binarycode(m): # arranging all data to our desired # format a = intpartbinary(m) b = decimalpartbinary(m) c =[] for i in range(0, len(a)): c.append(a[i]) c.append('.') for j in range(0, len(b)): c.append(b[j]) print('Binary code of given function is\\n') for k in range(0, len(c)): print(c[k], end =' ') # Driver Codebinarycode(123.5)", "e": 5992, "s": 5046, "text": null }, { "code": null, "e": 6000, "s": 5992, "text": "Output:" }, { "code": null, "e": 6053, "s": 6000, "text": "Binary code of given function is\n\n1 1 1 1 0 1 1 . 1 " }, { "code": null, "e": 6075, "s": 6053, "text": "binary-representation" }, { "code": null, "e": 6082, "s": 6075, "text": "Python" }, { "code": null, "e": 6098, "s": 6082, "text": "Python Programs" } ]
LocalTime compareTo() method in Java with Examples
03 Dec, 2018 The compareTo() method of a LocalTime class is used to compare this LocalTime object to the LocalTime passed as parameter to check whether both LocalTimes are equal. The comparison between both LocalTimes is based on timeline position of the local times within a day. The value to be returned by this method is determined as follows: if this LocalTime is greater than LocalTime passed as a parameter, then a positive value is returned if this LocalTime is equal to the LocalTime passed as a parameter, then a zero (0) is returned if this LocalTime is less than LocalTime passed as a parameter then a negative value is returned. Syntax: public int compareTo(LocalTime other) Parameters: This method accepts a single parameter LocalTime which is the other LocalTime to be compared, and it should not be null. Return Value: This method returns the int value and returned value is determined as follows: if this LocalTime is greater than LocalTime passed as a parameter, then a positive value is returned if this LocalTime is equal to the LocalTime passed as a parameter, then a zero (0) is returned if this LocalTime is less than LocalTime passed as a parameter then a negative value is returned. Below programs illustrate the compareTo() method: Program 1: When this LocalTime is greater // Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse("17:52:49"); LocalTime time2 = LocalTime.parse("13:08:00"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println("Int Value:" + value); if (value > 0) System.out.println("LocalTime1 is greater"); else if (value == 0) System.out.println("LocalTime1 is equal to" + " LocalTime2"); else System.out.println("LocalTime2 is greater"); }} Int Value:1 LocalTime1 is greater Program 2: When passed LocalTime is greater // Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse("07:12:29"); LocalTime time2 = LocalTime.parse("13:08:00"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println("Int Value:" + value); if (value > 0) System.out.println("LocalTime1 is greater"); else if (value == 0) System.out.println("LocalTime1 is equal to" + " LocalTime2"); else System.out.println("LocalTime2 is greater"); }} Int Value:-1 LocalTime2 is greater Program 3: When both Localtimes are equal // Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse("13:08:00"); LocalTime time2 = LocalTime.parse("13:08:00"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println("Int Value:" + value); if (value > 0) System.out.println("LocalTime1 is greater"); else if (value == 0) System.out.println("LocalTime1 is equal to" + " LocalTime2"); else System.out.println("LocalTime2 is greater"); }} Int Value:0 LocalTime1 is equal to LocalTime2 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#compareTo(java.time.LocalTime)) Java-Functions Java-LocalTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 362, "s": 28, "text": "The compareTo() method of a LocalTime class is used to compare this LocalTime object to the LocalTime passed as parameter to check whether both LocalTimes are equal. The comparison between both LocalTimes is based on timeline position of the local times within a day. The value to be returned by this method is determined as follows:" }, { "code": null, "e": 463, "s": 362, "text": "if this LocalTime is greater than LocalTime passed as a parameter, then a positive value is returned" }, { "code": null, "e": 558, "s": 463, "text": "if this LocalTime is equal to the LocalTime passed as a parameter, then a zero (0) is returned" }, { "code": null, "e": 656, "s": 558, "text": "if this LocalTime is less than LocalTime passed as a parameter then a negative value is returned." }, { "code": null, "e": 664, "s": 656, "text": "Syntax:" }, { "code": null, "e": 703, "s": 664, "text": "public int compareTo(LocalTime other)\n" }, { "code": null, "e": 836, "s": 703, "text": "Parameters: This method accepts a single parameter LocalTime which is the other LocalTime to be compared, and it should not be null." }, { "code": null, "e": 929, "s": 836, "text": "Return Value: This method returns the int value and returned value is determined as follows:" }, { "code": null, "e": 1030, "s": 929, "text": "if this LocalTime is greater than LocalTime passed as a parameter, then a positive value is returned" }, { "code": null, "e": 1125, "s": 1030, "text": "if this LocalTime is equal to the LocalTime passed as a parameter, then a zero (0) is returned" }, { "code": null, "e": 1223, "s": 1125, "text": "if this LocalTime is less than LocalTime passed as a parameter then a negative value is returned." }, { "code": null, "e": 1273, "s": 1223, "text": "Below programs illustrate the compareTo() method:" }, { "code": null, "e": 1315, "s": 1273, "text": "Program 1: When this LocalTime is greater" }, { "code": "// Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse(\"17:52:49\"); LocalTime time2 = LocalTime.parse(\"13:08:00\"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println(\"Int Value:\" + value); if (value > 0) System.out.println(\"LocalTime1 is greater\"); else if (value == 0) System.out.println(\"LocalTime1 is equal to\" + \" LocalTime2\"); else System.out.println(\"LocalTime2 is greater\"); }}", "e": 2073, "s": 1315, "text": null }, { "code": null, "e": 2108, "s": 2073, "text": "Int Value:1\nLocalTime1 is greater\n" }, { "code": null, "e": 2152, "s": 2108, "text": "Program 2: When passed LocalTime is greater" }, { "code": "// Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse(\"07:12:29\"); LocalTime time2 = LocalTime.parse(\"13:08:00\"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println(\"Int Value:\" + value); if (value > 0) System.out.println(\"LocalTime1 is greater\"); else if (value == 0) System.out.println(\"LocalTime1 is equal to\" + \" LocalTime2\"); else System.out.println(\"LocalTime2 is greater\"); }}", "e": 2910, "s": 2152, "text": null }, { "code": null, "e": 2946, "s": 2910, "text": "Int Value:-1\nLocalTime2 is greater\n" }, { "code": null, "e": 2988, "s": 2946, "text": "Program 3: When both Localtimes are equal" }, { "code": "// Java program to demonstrate// LocalTime.compareTo() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time1 = LocalTime.parse(\"13:08:00\"); LocalTime time2 = LocalTime.parse(\"13:08:00\"); // apply compareTo() int value = time1.compareTo(time2); // print LocalDateTime System.out.println(\"Int Value:\" + value); if (value > 0) System.out.println(\"LocalTime1 is greater\"); else if (value == 0) System.out.println(\"LocalTime1 is equal to\" + \" LocalTime2\"); else System.out.println(\"LocalTime2 is greater\"); }}", "e": 3746, "s": 2988, "text": null }, { "code": null, "e": 3793, "s": 3746, "text": "Int Value:0\nLocalTime1 is equal to LocalTime2\n" }, { "code": null, "e": 3904, "s": 3793, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#compareTo(java.time.LocalTime))" }, { "code": null, "e": 3919, "s": 3904, "text": "Java-Functions" }, { "code": null, "e": 3934, "s": 3919, "text": "Java-LocalTime" }, { "code": null, "e": 3952, "s": 3934, "text": "Java-time package" }, { "code": null, "e": 3957, "s": 3952, "text": "Java" }, { "code": null, "e": 3962, "s": 3957, "text": "Java" } ]