title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Improving the Stack Overflow search algorithm using Semantic Search and NLP | by Rohit Agrawal | Towards Data Science
If you a person who has ever tried to write a piece of code, you are sure to come across Stack Overflow (it’s that famous). For those who live under a rock, Stack Overflow provides one of the largest QA platforms for programmers. Users post questions/doubts and their fellow peers try to provide solutions in the most helpful manner possible. The better an answer, the higher the votes it gets, which also increase a user’s reputation. Given its popularity, it’s safe to say that there is a buttload of data on there. However, this huge amount of information also makes it difficult to search for the solution one is looking for. It’s not that big of an issue for programming veterans and other experienced professionals, because they are aware of the correct keywords required to get an appropriate answer. However, for a baby programmer, this poses a great concern. For instance, if he needs to learn ‘how to make a server’ using Python, it is quite unlikely that he would use the terms ‘Django’ or ‘Flask’ in the search box. Thus, this might intimidate the user to use the platform. Therefore, an optimal search engine is necessary to navigate through this mess. However, as it currently stands, the search engine of Stack Overflow suffers from a few bugs of its own. Let me illustrate it by an example: Let’s say that I’m a beginner in NodeJS and I want to run my app. So I go over to Stack Overflow and type the following: ‘Node — how to run node app.js?’. This is what I get: However, there does exist a result for ‘Node — how to run app.js?’: Ideally, it should have returned the result for both the queries, but it didn’t. ‘Houston, we have a problem!’ But why bother, you ask? A major source of income for Stack Overflow is through Ad Revenue. Therefore, their goal is to maximize user engagement to push more ads and thus earn more money. Due to the suboptimal performance of their search engine, a user would have difficulty getting his doubts cleared through their website and would thus decide to use a more sophisticated search engine like Google for their purposes. The problem arises when Google suggests a resource other than Stackoverflow. For every user that leaves their website, they lose money they could potentially make. Our objective is for the platform to actually understand the content of what the user is trying to search for, and then return the most similar results based on that. Natural Language Processing (NLP) has come a long way since its inception in the 20th century. This subfield of Artificial Intelligence has proven to work very well in the past few years due to fast processors and sophisticated model architectures and thus has immense potential for solving various language comprehension tasks. (To view the animated version, click here) The solution is broken into 2 subtasks: Tag Prediction: Given the user query, we would like to predict which tags the given query best belongs toInformation retrieval: Based on a user query, return an existing question which most closely resembles the user’s query Tag Prediction: Given the user query, we would like to predict which tags the given query best belongs to Information retrieval: Based on a user query, return an existing question which most closely resembles the user’s query Giving you a bird-eye view, the flow of the solution is as follows: Collecting Stackoverflow Question/Answer data from Google BigQuery Pre-processing and Normalizing the collected data Filter out only the most common tags (Used 500 tags) Training Word Embeddings using Word2Vec Training a Tag Classifier using an LSTM model (hint: you cannot use binary cross-entropy loss to train it. Read more to know why) Using the trained word embeddings to create sentence embeddings for all questions in our database Comparing a query to each sentence and ranking semantically similar results using a measure based on cosine distance. Creating a web application using ReactJS and Flask to deploy the trained model For people with flowchart fetishes, here you go: Nothing too flashy right? If you are familiar with each of these concepts, feel free to jump right into the code(It’s well documented as well *codegasm*). github.com Baby programmers, please keep reading :) Little side note: I won’t be explaining each and every line of code in the article (the jupyter notebooks in the repo already take care of that). Instead, I would be focusing on key results and the intuition behind them To understand and learn from the data, I need to gather Questions and Answers that were posted on Stack Overflow. Thus what I need are the following: Title Question body Answers for that question Votes for each answer Due to the sheer abundance of data on Stack Overflow and better sanity checks, I restricted the data to only “Python” related questions. However, the entire process in reproducible for other topics as well Google BigQuery dataset includes an archive of Stack Overflow content, including posts, votes, tags, and badges. This dataset is updated to mirror the Stack Overflow content on the Internet Archive and is also available through the Stack Exchange Data Explorer. More info about the dataset is given at Kaggle Stackoverflow Dataset The required data for our task can be collected through the following SQL Query: SELECT q.id, q.title, q.body, q.tags, a.body as answers, a.score FROM 'bigquery-public-data.stackoverflow.posts_questions' AS q INNER JOIN 'bigquery-public-data.stackoverflow.posts_answers' AS a ON q.id = a.parent_id WHERE q.tags LIKE '%python%' LIMIT 500000 This query joins 2 tables(stackoverflow.posts_questions and stackoverflow.posts_answers) and collects required data for 500000 questions which are related to python. Thus, each row contains a question and one of the answers it has. (Note: There may be rows with identical questions but unique answers). Data Preprocessing 101 — Check for missing values: df.isna().sum()--------------id 0title 0body 0tags 0answers 0score 0dtype: int64 As I mentioned before, our dataset may contain rows with identical questions but unique answers. We want to combine all these different rows as one while summing up the votes of each answer and combining all answers. Max score before: 5440 Max score after: 9730 Now that we have our raw data finally ready, we can move onto cleaning and preprocessing this raw text data. I implemented basic text processing including the following steps: Convert raw text into tokensConvert tokens to lower caseRemove punctuationsRemove Stopwords Convert raw text into tokens Convert tokens to lower case Remove punctuations Remove Stopwords Note: I skipped removal of numeric data since I felt it would remove precious contextual information. I also skipped a ‘Stemming/Lemmatization’ step because I did not want alter the domain specific terms used in our corpus and risk losing precious information If you notice the dataset closely, you’ll observe that the raw text for Questions and Answers is given along with the HTML markup with which it was displayed on StackOverflow originally. These refer usually to p tags, h1-h6 tags and the code tags. Since I only need the text section of each post, I performed the following steps: I constructed a new feature column called ‘post_corpus’ by combining the title, question body, and all the answers(Will be used later to train Word2Vec embeddings) I prepended the title to the question body I skipped the ‘code’ sections because they do not offer useful information for our task I constructed URLs for each question by appending ‘https://stackoverflow.com/questions/' with the question id I constructed 2 features for sentiment using the open Source Textblob library Each post has a variable number of different tags. To narrow down the vast choices for a more accurate model, I decided to with 20 most common tags. The plan is to filter only the data which contains at least one of most_common_tags ['python', 'python-3.x', 'django', 'pandas', 'python-2.7', 'numpy', 'list', 'matplotlib', 'dictionary', 'regex', 'dataframe', 'tkinter', 'string', 'csv', 'flask', 'arrays', 'tensorflow', 'json', 'beautifulsoup', 'selenium'] Alright, just one last quick boring as hell data processing step, then we get to the fun stuff :) I created a separate column for the ‘processed_title’ because I wanted to preserve the original title because I wanted to serve the original titles in the app I also normalized the numeric ‘scores’ Although we did filter out a lot of tags in the Data processing step, there still exist a lot of “stray” tags which may appear only once or twice as compared to thousands of occurrences for other tags. This increases the dimensions of the ground truth data, which is not desirable for our model. Thus we extract the top 500 tags based on their occurrences. (Given that we have ~140k data points, 500 tags seems to be a good number to experiment with) Finally, we altered the tag data to only include tags from one of these 500 tags, for better model accuracy For our model to understand the raw text data, we need to vectorize it. Bag of Words and TF-IDF are very common approaches for vectorizing. However, since I would be using an artificial neural network as my model(LSTM), the sparse nature of BOW and TFIDF would pose a problem. Thus I decided to go for Word Embeddings, which are dense vector representations and thus perfect for our neural network. The way people converse on StackOverflow is very technical and they use a very specific vocabulary of words, so it is not a good idea to use pre-trained Word Embeddings (although Google has a lot of good ones) because they are trained on plain English text such a Shakespeare and would not be able to understand the relations between the words in our vocabulary. Thus I decided to train a Word Embeddings model from scratch using Word2Vec. The column post_corpus in our dataset, comes to shine here. Since Word2Vec is an unsupervised model that just requires a corpus to train on, we need to provide it as much text as possible for it to understand the vocabulary. Thus we use post_corpus to train Word2Vec because it is a combination of the title, question, and all the answers for a post. After successful training, we get the following results: Terms most similar to "django"[('flask', 0.5827779173851013), ('project', 0.5168731212615967), ('mezzanine', 0.5122816562652588), ('wagtail', 0.5001770257949829), ('drf', 0.4827461242675781), ('framework', 0.48031285405158997), ('cms', 0.47275760769844055), ('admin', 0.467496395111084), ('database', 0.4659809470176697), ('app', 0.46219539642333984)]--------------------------------------------------------------------Terms most similar to "api"[('apis', 0.6121899485588074), ('webservice', 0.5226354598999023), ('service', 0.49891555309295654), ('framework', 0.4883273243904114), ('postman', 0.47500693798065186), ('webhook', 0.4574393630027771), ('rpc', 0.4385871887207031), ('oauth2', 0.41829735040664673), ('twilio', 0.4138619303703308), ('application', 0.4100519120693207)]--------------------------------------------------------------------Terms most similar to "gunicorn"[('uwsgi', 0.5529206991195679), ('nginx', 0.5103358030319214), ('000080', 0.4971828758716583), ('supervisord', 0.4751521050930023), ('arbiterpy', 0.4701758027076721), ('iis', 0.46567484736442566), ('apache2', 0.45948249101638794), ('web1', 0.45084959268569946), ('fastcgi', 0.43996310234069824), ('supervisor', 0.43604230880737305)]--------------------------------------------------------------------Terms most similar to "server"[('webserver', 0.5781407356262207), ('servers', 0.48877859115600586), ('application', 0.488214373588562), ('app', 0.4767988622188568), ('vps', 0.4679219126701355), ('client', 0.46672070026397705), ('localhost', 0.46468669176101685), ('service', 0.457424521446228), ('apache', 0.4540043771266937), ('nginx', 0.4490607976913452)] Pretty fricking cool, right? This section deals with our first subtask: “Given the user query, we would like to predict which tags the given query best belongs to” Preparing the data for training the model, includes: One-Hot encoding the ground truth dataSplitting into training and test setsTokenizing and PaddingCreating an embedding matrix One-Hot encoding the ground truth data Splitting into training and test sets Tokenizing and Padding Creating an embedding matrix (I’ll include the code here, however for detailed explanations for each section refer to the jupyter notebook in the repository) The model created for solving the subtask at hand used LSTM layers right after the Embedding layer because of their proficiency in working with sequential and text data. Subsequent Dense layers are added along with Dropout regularization to build a robust model The secret sauce — THE LOSS FUNCTION: Since we are dealing with a multilabel classification problem here, we cannot train the model using a binary cross-entropy loss. This is because binary cross-entropy loss would push your model to predict one or two tags which are included in the ground truth, and won’t penalize it for missing out on the other ones. Thus I used log loss applied on each class separately and then computed its average based on the number of classes. We can then get the tags for any sentence using the help of the following function: Test Case: selecting n1d array nd array numpy--------------------------------------------------------------------Predicted: [('arrays', 'numpy', 'python')]Ground Truth: [('numpy', 'python')]Test Case: taking info file--------------------------------------------------------------------Predicted: [('python',)]Ground Truth: [('python', 'python-2.6', 'python-2.7')]Test Case: python find txt continue causing fault--------------------------------------------------------------------Predicted: [('python',)]Ground Truth: [('python', 'python-3.x')]Test Case: fabric rsync read error connection reset peer 104--------------------------------------------------------------------Predicted: [('django', 'python')]Ground Truth: [('django', 'python', 'windows')]Test Case: fllter pandas dataframe multiple columns--------------------------------------------------------------------Predicted: [('dataframe', 'pandas', 'python')]Ground Truth: [('pandas', 'python')] It seems good enough for now 😃. Done with this subtask, moving onto the next lets gooo~ Subtask 2 demands the following: “Based on a user query, return an existing question which most closely resembles the user’s query” To compare how similar two sentences are, we can find the ‘distance’ between them. To be able to compute such a distance, the sentences must belong in the same vector space. This is done through sentence embeddings. One of the most popular distance measures, which I have also used, is the cosine distance. Lesser the cosine distance, higher is the similarity between the two vectors To calculate the embeddings for an entire sentence, I defined the following function which averages the embeddings for each valid token, and used to calculate sentence embeddings for all questions in our database: Although cosine distance alone is sufficient enough to give us a good result for this specific task, I decided to define a custom similarity measure. It is given as follows: where q = user query and t = an existing question It considers the cosine distance as a base measure It takes into account the popularity of the post based on the votes it has received by users at StackOverflow It takes into account the overall sentiment of the responses that people have made. A positive sentiment entails that the answers were helpful and thus is a good post Running the following code snippet can show you the algorithm in action: For user query “Combine lists of lists”, we get: The web application simply translates these results through a user interface I am not going to discuss how I created the web app in this post, you can check that code out in the repository itself. If you have any doubts or any constructive feedback (toxic haters can go suck a di..), please feel free to leave a response below. I’d love to hear from you 😄 Until then, Ciao~
[ { "code": null, "e": 608, "s": 172, "text": "If you a person who has ever tried to write a piece of code, you are sure to come across Stack Overflow (it’s that famous). For those who live under a rock, Stack Overflow provides one of the largest QA platforms for programmers. Users post questions/doubts and their fellow peers try to provide solutions in the most helpful manner possible. The better an answer, the higher the votes it gets, which also increase a user’s reputation." }, { "code": null, "e": 1258, "s": 608, "text": "Given its popularity, it’s safe to say that there is a buttload of data on there. However, this huge amount of information also makes it difficult to search for the solution one is looking for. It’s not that big of an issue for programming veterans and other experienced professionals, because they are aware of the correct keywords required to get an appropriate answer. However, for a baby programmer, this poses a great concern. For instance, if he needs to learn ‘how to make a server’ using Python, it is quite unlikely that he would use the terms ‘Django’ or ‘Flask’ in the search box. Thus, this might intimidate the user to use the platform." }, { "code": null, "e": 1479, "s": 1258, "text": "Therefore, an optimal search engine is necessary to navigate through this mess. However, as it currently stands, the search engine of Stack Overflow suffers from a few bugs of its own. Let me illustrate it by an example:" }, { "code": null, "e": 1654, "s": 1479, "text": "Let’s say that I’m a beginner in NodeJS and I want to run my app. So I go over to Stack Overflow and type the following: ‘Node — how to run node app.js?’. This is what I get:" }, { "code": null, "e": 1722, "s": 1654, "text": "However, there does exist a result for ‘Node — how to run app.js?’:" }, { "code": null, "e": 1803, "s": 1722, "text": "Ideally, it should have returned the result for both the queries, but it didn’t." }, { "code": null, "e": 1833, "s": 1803, "text": "‘Houston, we have a problem!’" }, { "code": null, "e": 2253, "s": 1833, "text": "But why bother, you ask? A major source of income for Stack Overflow is through Ad Revenue. Therefore, their goal is to maximize user engagement to push more ads and thus earn more money. Due to the suboptimal performance of their search engine, a user would have difficulty getting his doubts cleared through their website and would thus decide to use a more sophisticated search engine like Google for their purposes." }, { "code": null, "e": 2417, "s": 2253, "text": "The problem arises when Google suggests a resource other than Stackoverflow. For every user that leaves their website, they lose money they could potentially make." }, { "code": null, "e": 2584, "s": 2417, "text": "Our objective is for the platform to actually understand the content of what the user is trying to search for, and then return the most similar results based on that." }, { "code": null, "e": 2913, "s": 2584, "text": "Natural Language Processing (NLP) has come a long way since its inception in the 20th century. This subfield of Artificial Intelligence has proven to work very well in the past few years due to fast processors and sophisticated model architectures and thus has immense potential for solving various language comprehension tasks." }, { "code": null, "e": 2956, "s": 2913, "text": "(To view the animated version, click here)" }, { "code": null, "e": 2996, "s": 2956, "text": "The solution is broken into 2 subtasks:" }, { "code": null, "e": 3221, "s": 2996, "text": "Tag Prediction: Given the user query, we would like to predict which tags the given query best belongs toInformation retrieval: Based on a user query, return an existing question which most closely resembles the user’s query" }, { "code": null, "e": 3327, "s": 3221, "text": "Tag Prediction: Given the user query, we would like to predict which tags the given query best belongs to" }, { "code": null, "e": 3447, "s": 3327, "text": "Information retrieval: Based on a user query, return an existing question which most closely resembles the user’s query" }, { "code": null, "e": 3515, "s": 3447, "text": "Giving you a bird-eye view, the flow of the solution is as follows:" }, { "code": null, "e": 3582, "s": 3515, "text": "Collecting Stackoverflow Question/Answer data from Google BigQuery" }, { "code": null, "e": 3632, "s": 3582, "text": "Pre-processing and Normalizing the collected data" }, { "code": null, "e": 3685, "s": 3632, "text": "Filter out only the most common tags (Used 500 tags)" }, { "code": null, "e": 3725, "s": 3685, "text": "Training Word Embeddings using Word2Vec" }, { "code": null, "e": 3855, "s": 3725, "text": "Training a Tag Classifier using an LSTM model (hint: you cannot use binary cross-entropy loss to train it. Read more to know why)" }, { "code": null, "e": 3953, "s": 3855, "text": "Using the trained word embeddings to create sentence embeddings for all questions in our database" }, { "code": null, "e": 4071, "s": 3953, "text": "Comparing a query to each sentence and ranking semantically similar results using a measure based on cosine distance." }, { "code": null, "e": 4150, "s": 4071, "text": "Creating a web application using ReactJS and Flask to deploy the trained model" }, { "code": null, "e": 4199, "s": 4150, "text": "For people with flowchart fetishes, here you go:" }, { "code": null, "e": 4354, "s": 4199, "text": "Nothing too flashy right? If you are familiar with each of these concepts, feel free to jump right into the code(It’s well documented as well *codegasm*)." }, { "code": null, "e": 4365, "s": 4354, "text": "github.com" }, { "code": null, "e": 4406, "s": 4365, "text": "Baby programmers, please keep reading :)" }, { "code": null, "e": 4626, "s": 4406, "text": "Little side note: I won’t be explaining each and every line of code in the article (the jupyter notebooks in the repo already take care of that). Instead, I would be focusing on key results and the intuition behind them" }, { "code": null, "e": 4776, "s": 4626, "text": "To understand and learn from the data, I need to gather Questions and Answers that were posted on Stack Overflow. Thus what I need are the following:" }, { "code": null, "e": 4782, "s": 4776, "text": "Title" }, { "code": null, "e": 4796, "s": 4782, "text": "Question body" }, { "code": null, "e": 4822, "s": 4796, "text": "Answers for that question" }, { "code": null, "e": 4844, "s": 4822, "text": "Votes for each answer" }, { "code": null, "e": 5050, "s": 4844, "text": "Due to the sheer abundance of data on Stack Overflow and better sanity checks, I restricted the data to only “Python” related questions. However, the entire process in reproducible for other topics as well" }, { "code": null, "e": 5381, "s": 5050, "text": "Google BigQuery dataset includes an archive of Stack Overflow content, including posts, votes, tags, and badges. This dataset is updated to mirror the Stack Overflow content on the Internet Archive and is also available through the Stack Exchange Data Explorer. More info about the dataset is given at Kaggle Stackoverflow Dataset" }, { "code": null, "e": 5462, "s": 5381, "text": "The required data for our task can be collected through the following SQL Query:" }, { "code": null, "e": 5721, "s": 5462, "text": "SELECT q.id, q.title, q.body, q.tags, a.body as answers, a.score FROM 'bigquery-public-data.stackoverflow.posts_questions' AS q INNER JOIN 'bigquery-public-data.stackoverflow.posts_answers' AS a ON q.id = a.parent_id WHERE q.tags LIKE '%python%' LIMIT 500000" }, { "code": null, "e": 6024, "s": 5721, "text": "This query joins 2 tables(stackoverflow.posts_questions and stackoverflow.posts_answers) and collects required data for 500000 questions which are related to python. Thus, each row contains a question and one of the answers it has. (Note: There may be rows with identical questions but unique answers)." }, { "code": null, "e": 6075, "s": 6024, "text": "Data Preprocessing 101 — Check for missing values:" }, { "code": null, "e": 6189, "s": 6075, "text": "df.isna().sum()--------------id 0title 0body 0tags 0answers 0score 0dtype: int64" }, { "code": null, "e": 6406, "s": 6189, "text": "As I mentioned before, our dataset may contain rows with identical questions but unique answers. We want to combine all these different rows as one while summing up the votes of each answer and combining all answers." }, { "code": null, "e": 6453, "s": 6406, "text": "Max score before: 5440 Max score after: 9730" }, { "code": null, "e": 6629, "s": 6453, "text": "Now that we have our raw data finally ready, we can move onto cleaning and preprocessing this raw text data. I implemented basic text processing including the following steps:" }, { "code": null, "e": 6721, "s": 6629, "text": "Convert raw text into tokensConvert tokens to lower caseRemove punctuationsRemove Stopwords" }, { "code": null, "e": 6750, "s": 6721, "text": "Convert raw text into tokens" }, { "code": null, "e": 6779, "s": 6750, "text": "Convert tokens to lower case" }, { "code": null, "e": 6799, "s": 6779, "text": "Remove punctuations" }, { "code": null, "e": 6816, "s": 6799, "text": "Remove Stopwords" }, { "code": null, "e": 6918, "s": 6816, "text": "Note: I skipped removal of numeric data since I felt it would remove precious contextual information." }, { "code": null, "e": 7076, "s": 6918, "text": "I also skipped a ‘Stemming/Lemmatization’ step because I did not want alter the domain specific terms used in our corpus and risk losing precious information" }, { "code": null, "e": 7406, "s": 7076, "text": "If you notice the dataset closely, you’ll observe that the raw text for Questions and Answers is given along with the HTML markup with which it was displayed on StackOverflow originally. These refer usually to p tags, h1-h6 tags and the code tags. Since I only need the text section of each post, I performed the following steps:" }, { "code": null, "e": 7570, "s": 7406, "text": "I constructed a new feature column called ‘post_corpus’ by combining the title, question body, and all the answers(Will be used later to train Word2Vec embeddings)" }, { "code": null, "e": 7613, "s": 7570, "text": "I prepended the title to the question body" }, { "code": null, "e": 7701, "s": 7613, "text": "I skipped the ‘code’ sections because they do not offer useful information for our task" }, { "code": null, "e": 7811, "s": 7701, "text": "I constructed URLs for each question by appending ‘https://stackoverflow.com/questions/' with the question id" }, { "code": null, "e": 7889, "s": 7811, "text": "I constructed 2 features for sentiment using the open Source Textblob library" }, { "code": null, "e": 8122, "s": 7889, "text": "Each post has a variable number of different tags. To narrow down the vast choices for a more accurate model, I decided to with 20 most common tags. The plan is to filter only the data which contains at least one of most_common_tags" }, { "code": null, "e": 8365, "s": 8122, "text": "['python', 'python-3.x', 'django', 'pandas', 'python-2.7', 'numpy', 'list', 'matplotlib', 'dictionary', 'regex', 'dataframe', 'tkinter', 'string', 'csv', 'flask', 'arrays', 'tensorflow', 'json', 'beautifulsoup', 'selenium']" }, { "code": null, "e": 8463, "s": 8365, "text": "Alright, just one last quick boring as hell data processing step, then we get to the fun stuff :)" }, { "code": null, "e": 8622, "s": 8463, "text": "I created a separate column for the ‘processed_title’ because I wanted to preserve the original title because I wanted to serve the original titles in the app" }, { "code": null, "e": 8661, "s": 8622, "text": "I also normalized the numeric ‘scores’" }, { "code": null, "e": 8957, "s": 8661, "text": "Although we did filter out a lot of tags in the Data processing step, there still exist a lot of “stray” tags which may appear only once or twice as compared to thousands of occurrences for other tags. This increases the dimensions of the ground truth data, which is not desirable for our model." }, { "code": null, "e": 9112, "s": 8957, "text": "Thus we extract the top 500 tags based on their occurrences. (Given that we have ~140k data points, 500 tags seems to be a good number to experiment with)" }, { "code": null, "e": 9220, "s": 9112, "text": "Finally, we altered the tag data to only include tags from one of these 500 tags, for better model accuracy" }, { "code": null, "e": 9619, "s": 9220, "text": "For our model to understand the raw text data, we need to vectorize it. Bag of Words and TF-IDF are very common approaches for vectorizing. However, since I would be using an artificial neural network as my model(LSTM), the sparse nature of BOW and TFIDF would pose a problem. Thus I decided to go for Word Embeddings, which are dense vector representations and thus perfect for our neural network." }, { "code": null, "e": 10059, "s": 9619, "text": "The way people converse on StackOverflow is very technical and they use a very specific vocabulary of words, so it is not a good idea to use pre-trained Word Embeddings (although Google has a lot of good ones) because they are trained on plain English text such a Shakespeare and would not be able to understand the relations between the words in our vocabulary. Thus I decided to train a Word Embeddings model from scratch using Word2Vec." }, { "code": null, "e": 10410, "s": 10059, "text": "The column post_corpus in our dataset, comes to shine here. Since Word2Vec is an unsupervised model that just requires a corpus to train on, we need to provide it as much text as possible for it to understand the vocabulary. Thus we use post_corpus to train Word2Vec because it is a combination of the title, question, and all the answers for a post." }, { "code": null, "e": 10467, "s": 10410, "text": "After successful training, we get the following results:" }, { "code": null, "e": 12104, "s": 10467, "text": "Terms most similar to \"django\"[('flask', 0.5827779173851013), ('project', 0.5168731212615967), ('mezzanine', 0.5122816562652588), ('wagtail', 0.5001770257949829), ('drf', 0.4827461242675781), ('framework', 0.48031285405158997), ('cms', 0.47275760769844055), ('admin', 0.467496395111084), ('database', 0.4659809470176697), ('app', 0.46219539642333984)]--------------------------------------------------------------------Terms most similar to \"api\"[('apis', 0.6121899485588074), ('webservice', 0.5226354598999023), ('service', 0.49891555309295654), ('framework', 0.4883273243904114), ('postman', 0.47500693798065186), ('webhook', 0.4574393630027771), ('rpc', 0.4385871887207031), ('oauth2', 0.41829735040664673), ('twilio', 0.4138619303703308), ('application', 0.4100519120693207)]--------------------------------------------------------------------Terms most similar to \"gunicorn\"[('uwsgi', 0.5529206991195679), ('nginx', 0.5103358030319214), ('000080', 0.4971828758716583), ('supervisord', 0.4751521050930023), ('arbiterpy', 0.4701758027076721), ('iis', 0.46567484736442566), ('apache2', 0.45948249101638794), ('web1', 0.45084959268569946), ('fastcgi', 0.43996310234069824), ('supervisor', 0.43604230880737305)]--------------------------------------------------------------------Terms most similar to \"server\"[('webserver', 0.5781407356262207), ('servers', 0.48877859115600586), ('application', 0.488214373588562), ('app', 0.4767988622188568), ('vps', 0.4679219126701355), ('client', 0.46672070026397705), ('localhost', 0.46468669176101685), ('service', 0.457424521446228), ('apache', 0.4540043771266937), ('nginx', 0.4490607976913452)]" }, { "code": null, "e": 12133, "s": 12104, "text": "Pretty fricking cool, right?" }, { "code": null, "e": 12176, "s": 12133, "text": "This section deals with our first subtask:" }, { "code": null, "e": 12268, "s": 12176, "text": "“Given the user query, we would like to predict which tags the given query best belongs to”" }, { "code": null, "e": 12321, "s": 12268, "text": "Preparing the data for training the model, includes:" }, { "code": null, "e": 12447, "s": 12321, "text": "One-Hot encoding the ground truth dataSplitting into training and test setsTokenizing and PaddingCreating an embedding matrix" }, { "code": null, "e": 12486, "s": 12447, "text": "One-Hot encoding the ground truth data" }, { "code": null, "e": 12524, "s": 12486, "text": "Splitting into training and test sets" }, { "code": null, "e": 12547, "s": 12524, "text": "Tokenizing and Padding" }, { "code": null, "e": 12576, "s": 12547, "text": "Creating an embedding matrix" }, { "code": null, "e": 12705, "s": 12576, "text": "(I’ll include the code here, however for detailed explanations for each section refer to the jupyter notebook in the repository)" }, { "code": null, "e": 12967, "s": 12705, "text": "The model created for solving the subtask at hand used LSTM layers right after the Embedding layer because of their proficiency in working with sequential and text data. Subsequent Dense layers are added along with Dropout regularization to build a robust model" }, { "code": null, "e": 13322, "s": 12967, "text": "The secret sauce — THE LOSS FUNCTION: Since we are dealing with a multilabel classification problem here, we cannot train the model using a binary cross-entropy loss. This is because binary cross-entropy loss would push your model to predict one or two tags which are included in the ground truth, and won’t penalize it for missing out on the other ones." }, { "code": null, "e": 13438, "s": 13322, "text": "Thus I used log loss applied on each class separately and then computed its average based on the number of classes." }, { "code": null, "e": 13522, "s": 13438, "text": "We can then get the tags for any sentence using the help of the following function:" }, { "code": null, "e": 14476, "s": 13522, "text": "Test Case: selecting n1d array nd array numpy--------------------------------------------------------------------Predicted: [('arrays', 'numpy', 'python')]Ground Truth: [('numpy', 'python')]Test Case: taking info file--------------------------------------------------------------------Predicted: [('python',)]Ground Truth: [('python', 'python-2.6', 'python-2.7')]Test Case: python find txt continue causing fault--------------------------------------------------------------------Predicted: [('python',)]Ground Truth: [('python', 'python-3.x')]Test Case: fabric rsync read error connection reset peer 104--------------------------------------------------------------------Predicted: [('django', 'python')]Ground Truth: [('django', 'python', 'windows')]Test Case: fllter pandas dataframe multiple columns--------------------------------------------------------------------Predicted: [('dataframe', 'pandas', 'python')]Ground Truth: [('pandas', 'python')]" }, { "code": null, "e": 14564, "s": 14476, "text": "It seems good enough for now 😃. Done with this subtask, moving onto the next lets gooo~" }, { "code": null, "e": 14597, "s": 14564, "text": "Subtask 2 demands the following:" }, { "code": null, "e": 14696, "s": 14597, "text": "“Based on a user query, return an existing question which most closely resembles the user’s query”" }, { "code": null, "e": 15080, "s": 14696, "text": "To compare how similar two sentences are, we can find the ‘distance’ between them. To be able to compute such a distance, the sentences must belong in the same vector space. This is done through sentence embeddings. One of the most popular distance measures, which I have also used, is the cosine distance. Lesser the cosine distance, higher is the similarity between the two vectors" }, { "code": null, "e": 15294, "s": 15080, "text": "To calculate the embeddings for an entire sentence, I defined the following function which averages the embeddings for each valid token, and used to calculate sentence embeddings for all questions in our database:" }, { "code": null, "e": 15468, "s": 15294, "text": "Although cosine distance alone is sufficient enough to give us a good result for this specific task, I decided to define a custom similarity measure. It is given as follows:" }, { "code": null, "e": 15518, "s": 15468, "text": "where q = user query and t = an existing question" }, { "code": null, "e": 15569, "s": 15518, "text": "It considers the cosine distance as a base measure" }, { "code": null, "e": 15679, "s": 15569, "text": "It takes into account the popularity of the post based on the votes it has received by users at StackOverflow" }, { "code": null, "e": 15846, "s": 15679, "text": "It takes into account the overall sentiment of the responses that people have made. A positive sentiment entails that the answers were helpful and thus is a good post" }, { "code": null, "e": 15919, "s": 15846, "text": "Running the following code snippet can show you the algorithm in action:" }, { "code": null, "e": 15968, "s": 15919, "text": "For user query “Combine lists of lists”, we get:" }, { "code": null, "e": 16045, "s": 15968, "text": "The web application simply translates these results through a user interface" }, { "code": null, "e": 16324, "s": 16045, "text": "I am not going to discuss how I created the web app in this post, you can check that code out in the repository itself. If you have any doubts or any constructive feedback (toxic haters can go suck a di..), please feel free to leave a response below. I’d love to hear from you 😄" } ]
Bye-bye Python. Hello Julia!. As Python’s lifetime grinds to a halt... | by Ari Joury | Towards Data Science
Don’t get me wrong. Python’s popularity is still backed by a rock-solid community of computer scientists, data scientists and AI specialists. But if you’ve ever been at a dinner table with these people, you also know how much they rant about the weaknesses of Python. From being slow to requiring excessive testing, to producing runtime errors despite prior testing — there’s enough to be pissed off about. Which is why more and more programmers are adopting other languages — the top players being Julia, Go, and Rust. Julia is great for mathematical and technical tasks, while Go is awesome for modular programs, and Rust is the top choice for systems programming. Since data scientists and AI specialists deal with lots of mathematical problems, Julia is the winner for them. And even upon critical scrutiny, Julia has upsides that Python can’t beat. towardsdatascience.com When people create a new programming language, they do so because they want to keep the good features of old languages and fix the bad ones. In this sense, Guido van Rossum created Python in the late 1980s to improve ABC. The latter was too perfect for a programming language — while its rigidity made it easy to teach, it was hard to use in real life. In contrast, Python is quite pragmatic. You can see this in the Zen of Python, which reflects the intention that the creators have: Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.[...] Python still kept the good features of ABC: Readability, simplicity, and beginner-friendliness for example. But Python is far more robust and adapted to real life than ABC ever was. In the same sense, the creators of Julia want to keep the good parts of other languages and ditch the bad ones. But Julia is a lot more ambitious: instead of replacing one language, it wants to beat them all. This is how Julia’s creators say it: We are greedy: we want more.We want a language that's open source, with a liberal license. We want the speed of C with the dynamism of Ruby. We want a language that's homoiconic, with true macros like Lisp, but with obvious, familiar mathematical notation like Matlab. We want something as usable for general programming as Python, as easy for statistics as R, as natural for string processing as Perl, as powerful for linear algebra as Matlab, as good at gluing programs together as the shell. Something that is dirt simple to learn, yet keeps the most serious hackers happy. We want it interactive and we want it compiled. Julia wants to blend all upsides that currently exist, and not trade them off for the downsides in other languages. And even though Julia is a young language, it has already achieved a lot of the goals that the creators set. Julia can be used for everything from simple machine learning applications to enormous supercomputer simulations. To some extent, Python can do this, too — but Python somehow grew into the job. In contrast, Julia was built precisely for this stuff. From the bottom up. Julia’s creators wanted to make a language that is as fast as C — but what they created is even faster. Even though Python has become easier to speed up in recent years, its performance is still a far cry from what Julia can do. In 2017, Julia even joined the Petaflop Club — the small club of languages who can exceed speeds of one petaflop per second at peak performance. Apart from Julia, only C, C++ and Fortran are in the club right now. towardsdatascience.com With its more than 30 years of age, Python has an enormous and supportive community. There is hardly a Python-related question that you can’t get answered within one Google search. In contrast, the Julia community is pretty tiny. While this means that you might need to dig a bit further to find an answer, you might link up with the same people again and again. And this can turn into programmer-relationships that are beyond value. You don’t even need to know a single Julia-command to code in Julia. Not only can you use Python and C code within Julia. You can even use Julia within Python! Needless to say, this makes it extremely easy to patch up the weaknesses of your Python code. Or to stay productive while you’re still getting to know Julia. This is one of the strongest points of Python — its zillion well-maintained libraries. Julia doesn’t have many libraries, and users have complained that they’re not amazingly maintained (yet). But when you consider that Julia is a very young language with a limited amount of resources, the number of libraries that they already have is pretty impressive. Apart from the fact that Julia’s amount of libraries is growing, it can also interface with libraries from C and Fortran to handle plots, for example. Python is 100% dynamically typed. This means that the program decides at runtime whether a variable is a float or an integer, for example. While this is extremely beginner-friendly, it also introduces a whole host of possible bugs. This means that you need to test Python code in all possible scenarios — which is quite a dumb task that takes a lot of time. Since the Julia-creators also wanted it to be easy to learn, Julia fully supports dynamical typing. But in contrast to Python, you can introduce static types if you like — in the way they are present in C or Fortran, for example. This can save you a ton of time: Instead of finding excuses for not testing your code, you can specify the type wherever it makes sense. towardsdatascience.com While all these things sound pretty great, it’s important to keep in mind that Julia is still tiny compared to Python. One pretty good metric is the number of questions on StackOverflow: At this point in time, Python is tagged about twenty more often than Julia! This doesn’t mean that Julia is unpopular — rather, it’s naturally taking some time to get adopted by programmers. Think about it — would you really want to write your whole code in a different language? No, you’d rather try a new language in some future project. This creates a time lag that every programming language faces between its release and its adoption. But if you adopt it now — which is easy because Julia allows an enormous amount of language conversion — you’re investing in the future. As more and more people adopt Julia, you’ll already have gained enough experience to answer their questions. Also, your code will be more durable as more and more Python code is replaced by Julia. Forty years ago, artificial intelligence was nothing but a niche phenomenon. The industry and investors didn’t believe in it, and many technologies were clunky and hard to use. But those who learned it back then are the giants of today — those that are so high in demand that their salary matches that of an NFL player. Similarly, Julia is still very niche now. But when it grows, the big winners will be those who adopted it early. I’m not saying that you’re guaranteed to make a shitload of money in ten years if you adopt Julia now. But you’re increasing your chances. Think about it: Most programmers out there have Python on their CV. And in the next few years, we’ll see even more Python programmers on the job market. But if the demand of enterprises for Python slows, the perspectives for Python programmers are going to go down. Slowly at first, but inevitably. On the other hand, you have a real edge if you can put Julia on your CV. Because let’s be honest, what distinguishes you from any other Pythonista out there? Not much. But there won’t be that many Julia-programmers out there, even in three years’ time. With Julia-skills, not only are you showing that you have interests beyond the job requirements. You’re also demonstrating that you’re eager to learn and that you have a broader sense of what it means to be a programmer. In other words, you’re fit for the job. You — and the other Julia programmers — are future rockstars, and you know it. Or, as Julia’s creators said it in 2012: Even though we recognize that we are inexcusably greedy, we still want to have it all. About two and a half years ago, we set out to create the language of our greed. It's not complete, but it's time for a 1.0 release — the language we've created is called Julia. It already delivers on 90% of our ungracious demands, and now it needs the ungracious demands of others to shape it further. So, if you are also a greedy, unreasonable, demanding programmer, we want you to give it a try. Python is still insanely popular. But if you learn Julia now, that could be your golden ticket later on. In this sense: Bye-bye Python. Hello Julia! Edit: I’ve given a talk on Julia vs. Python! It was hosted by Hatchpad, and the video is here.
[ { "code": null, "e": 313, "s": 171, "text": "Don’t get me wrong. Python’s popularity is still backed by a rock-solid community of computer scientists, data scientists and AI specialists." }, { "code": null, "e": 578, "s": 313, "text": "But if you’ve ever been at a dinner table with these people, you also know how much they rant about the weaknesses of Python. From being slow to requiring excessive testing, to producing runtime errors despite prior testing — there’s enough to be pissed off about." }, { "code": null, "e": 838, "s": 578, "text": "Which is why more and more programmers are adopting other languages — the top players being Julia, Go, and Rust. Julia is great for mathematical and technical tasks, while Go is awesome for modular programs, and Rust is the top choice for systems programming." }, { "code": null, "e": 1025, "s": 838, "text": "Since data scientists and AI specialists deal with lots of mathematical problems, Julia is the winner for them. And even upon critical scrutiny, Julia has upsides that Python can’t beat." }, { "code": null, "e": 1048, "s": 1025, "text": "towardsdatascience.com" }, { "code": null, "e": 1189, "s": 1048, "text": "When people create a new programming language, they do so because they want to keep the good features of old languages and fix the bad ones." }, { "code": null, "e": 1401, "s": 1189, "text": "In this sense, Guido van Rossum created Python in the late 1980s to improve ABC. The latter was too perfect for a programming language — while its rigidity made it easy to teach, it was hard to use in real life." }, { "code": null, "e": 1533, "s": 1401, "text": "In contrast, Python is quite pragmatic. You can see this in the Zen of Python, which reflects the intention that the creators have:" }, { "code": null, "e": 1831, "s": 1533, "text": "Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.[...]" }, { "code": null, "e": 2013, "s": 1831, "text": "Python still kept the good features of ABC: Readability, simplicity, and beginner-friendliness for example. But Python is far more robust and adapted to real life than ABC ever was." }, { "code": null, "e": 2222, "s": 2013, "text": "In the same sense, the creators of Julia want to keep the good parts of other languages and ditch the bad ones. But Julia is a lot more ambitious: instead of replacing one language, it wants to beat them all." }, { "code": null, "e": 2259, "s": 2222, "text": "This is how Julia’s creators say it:" }, { "code": null, "e": 2884, "s": 2259, "text": "We are greedy: we want more.We want a language that's open source, with a liberal license. We want the speed of C with the dynamism of Ruby. We want a language that's homoiconic, with true macros like Lisp, but with obvious, familiar mathematical notation like Matlab. We want something as usable for general programming as Python, as easy for statistics as R, as natural for string processing as Perl, as powerful for linear algebra as Matlab, as good at gluing programs together as the shell. Something that is dirt simple to learn, yet keeps the most serious hackers happy. We want it interactive and we want it compiled." }, { "code": null, "e": 3109, "s": 2884, "text": "Julia wants to blend all upsides that currently exist, and not trade them off for the downsides in other languages. And even though Julia is a young language, it has already achieved a lot of the goals that the creators set." }, { "code": null, "e": 3303, "s": 3109, "text": "Julia can be used for everything from simple machine learning applications to enormous supercomputer simulations. To some extent, Python can do this, too — but Python somehow grew into the job." }, { "code": null, "e": 3378, "s": 3303, "text": "In contrast, Julia was built precisely for this stuff. From the bottom up." }, { "code": null, "e": 3607, "s": 3378, "text": "Julia’s creators wanted to make a language that is as fast as C — but what they created is even faster. Even though Python has become easier to speed up in recent years, its performance is still a far cry from what Julia can do." }, { "code": null, "e": 3821, "s": 3607, "text": "In 2017, Julia even joined the Petaflop Club — the small club of languages who can exceed speeds of one petaflop per second at peak performance. Apart from Julia, only C, C++ and Fortran are in the club right now." }, { "code": null, "e": 3844, "s": 3821, "text": "towardsdatascience.com" }, { "code": null, "e": 4025, "s": 3844, "text": "With its more than 30 years of age, Python has an enormous and supportive community. There is hardly a Python-related question that you can’t get answered within one Google search." }, { "code": null, "e": 4278, "s": 4025, "text": "In contrast, the Julia community is pretty tiny. While this means that you might need to dig a bit further to find an answer, you might link up with the same people again and again. And this can turn into programmer-relationships that are beyond value." }, { "code": null, "e": 4438, "s": 4278, "text": "You don’t even need to know a single Julia-command to code in Julia. Not only can you use Python and C code within Julia. You can even use Julia within Python!" }, { "code": null, "e": 4596, "s": 4438, "text": "Needless to say, this makes it extremely easy to patch up the weaknesses of your Python code. Or to stay productive while you’re still getting to know Julia." }, { "code": null, "e": 4789, "s": 4596, "text": "This is one of the strongest points of Python — its zillion well-maintained libraries. Julia doesn’t have many libraries, and users have complained that they’re not amazingly maintained (yet)." }, { "code": null, "e": 5103, "s": 4789, "text": "But when you consider that Julia is a very young language with a limited amount of resources, the number of libraries that they already have is pretty impressive. Apart from the fact that Julia’s amount of libraries is growing, it can also interface with libraries from C and Fortran to handle plots, for example." }, { "code": null, "e": 5242, "s": 5103, "text": "Python is 100% dynamically typed. This means that the program decides at runtime whether a variable is a float or an integer, for example." }, { "code": null, "e": 5461, "s": 5242, "text": "While this is extremely beginner-friendly, it also introduces a whole host of possible bugs. This means that you need to test Python code in all possible scenarios — which is quite a dumb task that takes a lot of time." }, { "code": null, "e": 5691, "s": 5461, "text": "Since the Julia-creators also wanted it to be easy to learn, Julia fully supports dynamical typing. But in contrast to Python, you can introduce static types if you like — in the way they are present in C or Fortran, for example." }, { "code": null, "e": 5828, "s": 5691, "text": "This can save you a ton of time: Instead of finding excuses for not testing your code, you can specify the type wherever it makes sense." }, { "code": null, "e": 5851, "s": 5828, "text": "towardsdatascience.com" }, { "code": null, "e": 5970, "s": 5851, "text": "While all these things sound pretty great, it’s important to keep in mind that Julia is still tiny compared to Python." }, { "code": null, "e": 6114, "s": 5970, "text": "One pretty good metric is the number of questions on StackOverflow: At this point in time, Python is tagged about twenty more often than Julia!" }, { "code": null, "e": 6229, "s": 6114, "text": "This doesn’t mean that Julia is unpopular — rather, it’s naturally taking some time to get adopted by programmers." }, { "code": null, "e": 6478, "s": 6229, "text": "Think about it — would you really want to write your whole code in a different language? No, you’d rather try a new language in some future project. This creates a time lag that every programming language faces between its release and its adoption." }, { "code": null, "e": 6812, "s": 6478, "text": "But if you adopt it now — which is easy because Julia allows an enormous amount of language conversion — you’re investing in the future. As more and more people adopt Julia, you’ll already have gained enough experience to answer their questions. Also, your code will be more durable as more and more Python code is replaced by Julia." }, { "code": null, "e": 7132, "s": 6812, "text": "Forty years ago, artificial intelligence was nothing but a niche phenomenon. The industry and investors didn’t believe in it, and many technologies were clunky and hard to use. But those who learned it back then are the giants of today — those that are so high in demand that their salary matches that of an NFL player." }, { "code": null, "e": 7245, "s": 7132, "text": "Similarly, Julia is still very niche now. But when it grows, the big winners will be those who adopted it early." }, { "code": null, "e": 7384, "s": 7245, "text": "I’m not saying that you’re guaranteed to make a shitload of money in ten years if you adopt Julia now. But you’re increasing your chances." }, { "code": null, "e": 7683, "s": 7384, "text": "Think about it: Most programmers out there have Python on their CV. And in the next few years, we’ll see even more Python programmers on the job market. But if the demand of enterprises for Python slows, the perspectives for Python programmers are going to go down. Slowly at first, but inevitably." }, { "code": null, "e": 7936, "s": 7683, "text": "On the other hand, you have a real edge if you can put Julia on your CV. Because let’s be honest, what distinguishes you from any other Pythonista out there? Not much. But there won’t be that many Julia-programmers out there, even in three years’ time." }, { "code": null, "e": 8197, "s": 7936, "text": "With Julia-skills, not only are you showing that you have interests beyond the job requirements. You’re also demonstrating that you’re eager to learn and that you have a broader sense of what it means to be a programmer. In other words, you’re fit for the job." }, { "code": null, "e": 8317, "s": 8197, "text": "You — and the other Julia programmers — are future rockstars, and you know it. Or, as Julia’s creators said it in 2012:" }, { "code": null, "e": 8802, "s": 8317, "text": "Even though we recognize that we are inexcusably greedy, we still want to have it all. About two and a half years ago, we set out to create the language of our greed. It's not complete, but it's time for a 1.0 release — the language we've created is called Julia. It already delivers on 90% of our ungracious demands, and now it needs the ungracious demands of others to shape it further. So, if you are also a greedy, unreasonable, demanding programmer, we want you to give it a try." }, { "code": null, "e": 8951, "s": 8802, "text": "Python is still insanely popular. But if you learn Julia now, that could be your golden ticket later on. In this sense: Bye-bye Python. Hello Julia!" } ]
OpenCV - Adaptive Threshold
In simple thresholding, the threshold value is global, i.e., it is same for all the pixels in the image. Adaptive thresholding is the method where the threshold value is calculated for smaller regions and therefore, there will be different threshold values for different regions. In OpenCV, you can perform Adaptive threshold operation on an image using the method adaptiveThreshold() of the Imgproc class. Following is the syntax of this method. adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C) This method accepts the following parameters − src − An object of the class Mat representing the source (input) image. src − An object of the class Mat representing the source (input) image. dst − An object of the class Mat representing the destination (output) image. dst − An object of the class Mat representing the destination (output) image. maxValue − A variable of double type representing the value that is to be given if pixel value is more than the threshold value. maxValue − A variable of double type representing the value that is to be given if pixel value is more than the threshold value. adaptiveMethod − A variable of integer the type representing the adaptive method to be used. This will be either of the following two values ADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area. ADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window. adaptiveMethod − A variable of integer the type representing the adaptive method to be used. This will be either of the following two values ADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area. ADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area. ADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window. ADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window. thresholdType − A variable of integer type representing the type of threshold to be used. thresholdType − A variable of integer type representing the type of threshold to be used. blockSize − A variable of the integer type representing size of the pixelneighborhood used to calculate the threshold value. blockSize − A variable of the integer type representing size of the pixelneighborhood used to calculate the threshold value. C − A variable of double type representing the constant used in the both methods (subtracted from the mean or weighted mean). C − A variable of double type representing the constant used in the both methods (subtracted from the mean or weighted mean). The following program demonstrates how to perform Adaptive threshold operation on an image in OpenCV. Here we are choosing adaptive threshold of type binary and ADAPTIVE_THRESH_MEAN_C for threshold method. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class AdaptiveThresh { public static void main(String args[]) throws Exception { // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file ="E:/OpenCV/chap14/thresh_input.jpg"; // Reading the image Mat src = Imgcodecs.imread(file,0); // Creating an empty matrix to store the result Mat dst = new Mat(); Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 11, 12); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap14/Adaptivemean_thresh_binary.jpg", dst); System.out.println("Image Processed"); } } Assume that following is the input image thresh_input.jpg specified in the above program. On executing the program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − In addition to the ADAPTIVE_THRESH_MEAN_C as the adaptive method and THRESH_BINARY as the threshold type as demonstrated in the previous example, we can choose more combinations of these two values. Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 11, 12); Following are the values representing various combinations of values for the parameters adaptiveMethod and thresholdType and their respective outputs. 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3284, "s": 3004, "text": "In simple thresholding, the threshold value is global, i.e., it is same for all the pixels in the image. Adaptive thresholding is the method where the threshold value is calculated for smaller regions and therefore, there will be different threshold values for different regions." }, { "code": null, "e": 3451, "s": 3284, "text": "In OpenCV, you can perform Adaptive threshold operation on an image using the method adaptiveThreshold() of the Imgproc class. Following is the syntax of this method." }, { "code": null, "e": 3535, "s": 3451, "text": "adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C)\n" }, { "code": null, "e": 3582, "s": 3535, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3654, "s": 3582, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3726, "s": 3654, "text": "src − An object of the class Mat representing the source (input) image." }, { "code": null, "e": 3804, "s": 3726, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 3882, "s": 3804, "text": "dst − An object of the class Mat representing the destination (output) image." }, { "code": null, "e": 4011, "s": 3882, "text": "maxValue − A variable of double type representing the value that is to be given if pixel value is more than the threshold value." }, { "code": null, "e": 4140, "s": 4011, "text": "maxValue − A variable of double type representing the value that is to be given if pixel value is more than the threshold value." }, { "code": null, "e": 4484, "s": 4140, "text": "adaptiveMethod − A variable of integer the type representing the adaptive method to be used. This will be either of the following two values\n\nADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area.\nADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window.\n\n" }, { "code": null, "e": 4625, "s": 4484, "text": "adaptiveMethod − A variable of integer the type representing the adaptive method to be used. This will be either of the following two values" }, { "code": null, "e": 4700, "s": 4625, "text": "ADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area." }, { "code": null, "e": 4775, "s": 4700, "text": "ADAPTIVE_THRESH_MEAN_C − threshold value is the mean of neighborhood area." }, { "code": null, "e": 4900, "s": 4775, "text": "ADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window." }, { "code": null, "e": 5025, "s": 4900, "text": "ADAPTIVE_THRESH_GAUSSIAN_C − threshold value is the weighted sum of neighborhood values where weights are a Gaussian window." }, { "code": null, "e": 5115, "s": 5025, "text": "thresholdType − A variable of integer type representing the type of threshold to be used." }, { "code": null, "e": 5205, "s": 5115, "text": "thresholdType − A variable of integer type representing the type of threshold to be used." }, { "code": null, "e": 5330, "s": 5205, "text": "blockSize − A variable of the integer type representing size of the pixelneighborhood used to calculate the threshold value." }, { "code": null, "e": 5455, "s": 5330, "text": "blockSize − A variable of the integer type representing size of the pixelneighborhood used to calculate the threshold value." }, { "code": null, "e": 5581, "s": 5455, "text": "C − A variable of double type representing the constant used in the both methods (subtracted from the mean or weighted mean)." }, { "code": null, "e": 5707, "s": 5581, "text": "C − A variable of double type representing the constant used in the both methods (subtracted from the mean or weighted mean)." }, { "code": null, "e": 5913, "s": 5707, "text": "The following program demonstrates how to perform Adaptive threshold operation on an image in OpenCV. Here we are choosing adaptive threshold of type binary and ADAPTIVE_THRESH_MEAN_C for threshold method." }, { "code": null, "e": 6808, "s": 5913, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class AdaptiveThresh {\n public static void main(String args[]) throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap14/thresh_input.jpg\";\n \n // Reading the image\n Mat src = Imgcodecs.imread(file,0);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C,\n Imgproc.THRESH_BINARY, 11, 12);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap14/Adaptivemean_thresh_binary.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n } \n}" }, { "code": null, "e": 6898, "s": 6808, "text": "Assume that following is the input image thresh_input.jpg specified in the above program." }, { "code": null, "e": 6960, "s": 6898, "text": "On executing the program, you will get the following output −" }, { "code": null, "e": 6977, "s": 6960, "text": "Image Processed\n" }, { "code": null, "e": 7055, "s": 6977, "text": "If you open the specified path, you can observe the output image as follows −" }, { "code": null, "e": 7254, "s": 7055, "text": "In addition to the ADAPTIVE_THRESH_MEAN_C as the adaptive method and THRESH_BINARY as the threshold type as demonstrated in the previous example, we can choose more combinations of these two values." }, { "code": null, "e": 7364, "s": 7254, "text": "Imgproc.adaptiveThreshold(src, dst, 125, Imgproc.ADAPTIVE_THRESH_MEAN_C, \n Imgproc.THRESH_BINARY, 11, 12);\n" }, { "code": null, "e": 7515, "s": 7364, "text": "Following are the values representing various combinations of values for the parameters adaptiveMethod and thresholdType and their respective outputs." }, { "code": null, "e": 7548, "s": 7515, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 7565, "s": 7548, "text": " Abhilash Nelson" }, { "code": null, "e": 7598, "s": 7565, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 7615, "s": 7598, "text": " Abhilash Nelson" }, { "code": null, "e": 7648, "s": 7615, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7662, "s": 7648, "text": " Spotle Learn" }, { "code": null, "e": 7694, "s": 7662, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 7711, "s": 7694, "text": " Srikanth Guskra" }, { "code": null, "e": 7744, "s": 7711, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 7759, "s": 7744, "text": " Haithem Gasmi" }, { "code": null, "e": 7794, "s": 7759, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7812, "s": 7794, "text": " Gianluca Mottola" }, { "code": null, "e": 7819, "s": 7812, "text": " Print" }, { "code": null, "e": 7830, "s": 7819, "text": " Add Notes" } ]
Convert string to char array in Java
The following is our string. String str = "Tutorial"; Now, use the toCharArray() method to convert string to char array. char[] ch = str.toCharArray(); Now let us see the complete example. Live Demo public class Demo { public static void main(String []args) { String str = "Tutorial"; System.out.println("String: "+str); char[] ch = str.toCharArray(); System.out.println("Character Array..."); for (int i = 0; i < ch.length; i++) { System.out.print(ch[i]+" "); } } } String: Tutorial Character Array... T u t o r i a l
[ { "code": null, "e": 1091, "s": 1062, "text": "The following is our string." }, { "code": null, "e": 1116, "s": 1091, "text": "String str = \"Tutorial\";" }, { "code": null, "e": 1183, "s": 1116, "text": "Now, use the toCharArray() method to convert string to char array." }, { "code": null, "e": 1214, "s": 1183, "text": "char[] ch = str.toCharArray();" }, { "code": null, "e": 1251, "s": 1214, "text": "Now let us see the complete example." }, { "code": null, "e": 1262, "s": 1251, "text": " Live Demo" }, { "code": null, "e": 1581, "s": 1262, "text": "public class Demo {\n public static void main(String []args) {\n String str = \"Tutorial\";\n System.out.println(\"String: \"+str);\n char[] ch = str.toCharArray();\n System.out.println(\"Character Array...\");\n for (int i = 0; i < ch.length; i++) {\n System.out.print(ch[i]+\" \");\n }\n }\n}" }, { "code": null, "e": 1633, "s": 1581, "text": "String: Tutorial\nCharacter Array...\nT u t o r i a l" } ]
JavaFX - 2D Shapes Path Element Line
The path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape. This class has 2 properties of the double datatype namely − X − The x coordinate of the point to which a line is to be drawn from the current position. X − The x coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. To draw a line, you need to pass values to these properties. This can be either done by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below − LineTO line = new LineTo(x, y); Or, by using their respective setter methods as follows − setX(value); setY(value); To draw a line to a specified point from the current position in JavaFX, follow the steps given below. Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create the path class object as shown below. //Creating a Path object Path path = new Path(); Create the MoveTo path element and set the XY coordinates to starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below. //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); Create the path element line by instantiating the class named LineTo which belongs to the package javafx.scene.shape as follows. //Creating an object of the class LineTo LineTo lineTo = new LineTo(); Specify the coordinates of the point to which a line is to be drawn from the current position. This can be done by setting the properties x and y using their respective setter methods as shown in the following code block. //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); Add the path elements MoveTo and LineTo created in the previous steps to the observable list of the Path class as shown below − //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); Create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Line (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as shown below − Group root = new Group(line); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step. In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below − primaryStage.setScene(scene) Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } The following program shows how to draw a straight line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name LineToExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class LineToExample extends Application { @Override public void start(Stage stage) { //Creating a Path object Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); //Instantiating the LineTo class LineTo lineTo = new LineTo(); //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); //Creating a Group object Group root = new Group(path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Line"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac LineToExample.java java LineToExample On executing, the above program generates a JavaFX window displaying a straight line, which is drawn from the current position to the specified point, as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2021, "s": 1900, "text": "The path element line is used to draw a straight line to a point in the specified coordinates from the current position." }, { "code": null, "e": 2118, "s": 2021, "text": "It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 2178, "s": 2118, "text": "This class has 2 properties of the double datatype namely −" }, { "code": null, "e": 2270, "s": 2178, "text": "X − The x coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 2362, "s": 2270, "text": "X − The x coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 2454, "s": 2362, "text": "Y − The y coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 2546, "s": 2454, "text": "Y − The y coordinate of the point to which a line is to be drawn from the current position." }, { "code": null, "e": 2747, "s": 2546, "text": "To draw a line, you need to pass values to these properties. This can be either done by passing them to the constructor of this class, in the same order, at the time of instantiation, as shown below −" }, { "code": null, "e": 2780, "s": 2747, "text": "LineTO line = new LineTo(x, y);\n" }, { "code": null, "e": 2838, "s": 2780, "text": "Or, by using their respective setter methods as follows −" }, { "code": null, "e": 2866, "s": 2838, "text": "setX(value); \nsetY(value);\n" }, { "code": null, "e": 2969, "s": 2866, "text": "To draw a line to a specified point from the current position in JavaFX, follow the steps given below." }, { "code": null, "e": 3116, "s": 2969, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows." }, { "code": null, "e": 3257, "s": 3116, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 3310, "s": 3257, "text": "You can create the path class object as shown below." }, { "code": null, "e": 3361, "s": 3310, "text": "//Creating a Path object \nPath path = new Path();\n" }, { "code": null, "e": 3569, "s": 3361, "text": "Create the MoveTo path element and set the XY coordinates to starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below." }, { "code": null, "e": 3676, "s": 3569, "text": "//Moving to the starting point \nMoveTo moveTo = new MoveTo(); \nmoveTo.setX(100.0f); \nmoveTo.setY(150.0f);\n" }, { "code": null, "e": 3805, "s": 3676, "text": "Create the path element line by instantiating the class named LineTo which belongs to the package javafx.scene.shape as follows." }, { "code": null, "e": 3880, "s": 3805, "text": "//Creating an object of the class LineTo \nLineTo lineTo = new LineTo(); \n" }, { "code": null, "e": 4102, "s": 3880, "text": "Specify the coordinates of the point to which a line is to be drawn from the current position. This can be done by setting the properties x and y using their respective setter methods as shown in the following code block." }, { "code": null, "e": 4192, "s": 4102, "text": "//Setting the Properties of the line element \nlineTo.setX(500.0f); \nlineTo.setY(150.0f);\n" }, { "code": null, "e": 4320, "s": 4192, "text": "Add the path elements MoveTo and LineTo created in the previous steps to the observable list of the Path class as shown below −" }, { "code": null, "e": 4454, "s": 4320, "text": "//Adding the path elements to Observable list of the Path class \npath.getElements().add(moveTo); \npath.getElements().add(lineTo); \n" }, { "code": null, "e": 4559, "s": 4454, "text": "Create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 4739, "s": 4559, "text": "Pass the Line (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as shown below −" }, { "code": null, "e": 4770, "s": 4739, "text": "Group root = new Group(line);\n" }, { "code": null, "e": 4941, "s": 4770, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step." }, { "code": null, "e": 5110, "s": 4941, "text": "In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows." }, { "code": null, "e": 5153, "s": 5110, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 5343, "s": 5153, "text": "You can set the title to the stage using the setTitle() method of the stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter." }, { "code": null, "e": 5435, "s": 5343, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 5481, "s": 5435, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 5662, "s": 5481, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below −" }, { "code": null, "e": 5692, "s": 5662, "text": "primaryStage.setScene(scene)\n" }, { "code": null, "e": 5787, "s": 5692, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 5809, "s": 5787, "text": "primaryStage.show();\n" }, { "code": null, "e": 5935, "s": 5809, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 6003, "s": 5935, "text": "public static void main(String args[]){ \n launch(args); \n}" }, { "code": null, "e": 6197, "s": 6003, "text": "The following program shows how to draw a straight line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name LineToExample.java." }, { "code": null, "e": 7588, "s": 6197, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.LineTo; \nimport javafx.scene.shape.MoveTo; \nimport javafx.scene.shape.Path; \nimport javafx.stage.Stage; \n\npublic class LineToExample extends Application { \n @Override \n public void start(Stage stage) {\n //Creating a Path object \n Path path = new Path(); \n \n //Moving to the starting point \n MoveTo moveTo = new MoveTo(); \n moveTo.setX(100.0f); \n moveTo.setY(150.0f); \n \n //Instantiating the LineTo class \n LineTo lineTo = new LineTo(); \n \n //Setting the Properties of the line element \n lineTo.setX(500.0f); \n lineTo.setY(150.0f); \n \n //Adding the path elements to Observable list of the Path class \n path.getElements().add(moveTo); \n path.getElements().add(lineTo); \n \n //Creating a Group object \n Group root = new Group(path); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Line\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n }\n public static void main(String args[]){ \n launch(args); \n } \n} " }, { "code": null, "e": 7682, "s": 7588, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 7728, "s": 7682, "text": "javac LineToExample.java \njava LineToExample\n" }, { "code": null, "e": 7895, "s": 7728, "text": "On executing, the above program generates a JavaFX window displaying a straight line, which is drawn from the current position to the specified point, as shown below." }, { "code": null, "e": 7930, "s": 7895, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7941, "s": 7930, "text": " Syed Raza" }, { "code": null, "e": 7977, "s": 7941, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 8013, "s": 7977, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8046, "s": 8013, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 8082, "s": 8046, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8089, "s": 8082, "text": " Print" }, { "code": null, "e": 8100, "s": 8089, "text": " Add Notes" } ]
Kubernetes Application Deployment with AWS EKS and ECR | by Janitha Tennakoon | Towards Data Science
Kubernetes is a container orchestration platform that is created by Google in 2014. It is an open-source platform where currently many organizations widely use for container deployment and management. Although there are other container orchestration tools are available in the community like Docker Swarm, Kubernetes remains in the top for container orchestration due to its features and flexible usability. Amazon Elastic Kubernetes Service is a service provided for Kubernetes on AWS infrastructure. Like any other service offered by AWS, Kubernetes resources will be fully managed by AWS themselves, which gives less overload for developers on maintaining them. AWS also make sure that these resources are highly available and reliable every time. Amazon Elastic Container Registry is a fully managed Docker registry provided by AWS. Just like the popular docker registry Dockerhub, ECR also supports private and public repositories which are very secure. We can either push or pull images to ECR using AWS CLI. In this article, we are going to explore how we can deploy Kubernetes applications using AWS EKS and ECR services. Before going into complex details about how we are going to implement our Kubernetes solution below is the summary of tasks that we will be performing. Create a simple web application using Node.js Create a docker image of the web application Push our docker image to AWS ECR Create a VPC with public and private subnets for our EKS Cluster Create a Kubernetes Cluster Create Kubernetes workers(public and private workers) Deploy our web application on Kubernetes Now I hope you have at least a little bit of an idea about what we are going to cover in this article. Before we start implementing we need to have the following prerequisites available in our development machines. Kubectl — communication tool we will use to communicate between our Kubernetes cluster and our machine. Installation instructions available on https://kubernetes.io/docs/tasks/tools/install-kubectl/ AWS CLI — AWS tool which we will use to issue commands related to AWS configurations. To install follow https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html Aws iam authenticator — Give permission with IAM roles to access our Kubernetes cluster. For installation https://docs.aws.amazon.com/eks/latest/userguide/install-aws-iam-authenticator.html eksctl — Official CLI tool for AWS EKS. For installation https://github.com/weaveworks/eksctl After fulfilling our prerequisites first task will be to creating a simple server. I am using Node.js with express to create a very simple web application that will be listening on port 3000. Next, let’s dockerize our web application. For that create a Dockerfile and issue docker build command. docker build -t webapp . Now if you issue docker images we will see our webapp image. The next task is to push our image to AWS ECR. Before we can push the image we need to create a repository on ECR. For that go to the ECR dashboard and click Create Repository. Now we have a repository to push our image. But before that, we need to authenticate our AWS CLI to push images to our repository. For that issue below command. (Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com After that tag the image with our repository name. Here as the version, you can give any version, but in this instance, I am going to make the version as latest. docker tag webapp:latest 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com/eks-demo:latest Now the last step, push our image to the ECR repository. docker push 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com/eks-demo:latest If you get any permission issues make sure your AWS CLI role has permission AmazonEC2ContainerRegistryFullAccess. Now go to our repository and the image we pushed should be available there. The next step would be to create our EKS cluster. When we create our cluster, we need to specify the VPC subnets for our cluster to use. Amazon EKS requires subnets in at least two Availability Zones. When creating VPC we have two options. Create public and private subnets Create only public subnets In this article, we are going to create a combination of public and private subnets. In that case, our web application can be externally accessed by using a public subnet, also if we need to deploy something like database then we can make them private which will be only accessible by our web application and any other application within the VPC. VPC for our cluster can be created manually if we want. But let’s create our VPC using AWS Cloudformation because AWS already has a template for creating a public and private subnet VPC. Go to CloudFormation dashboard and select Create Stack Here select template source as Amazon S3 URL and provide the following template already created by AWS. https://amazon-eks.s3.us-west-2.amazonaws.com/cloudformation/2020-06-10/amazon-eks-vpc-private-subnets.yaml VPC will have CIDR addresses of 192.168.0.0/16 Create two public subnets with CIDR blocks 192.168.0.0/18 and 192.168.64.0/18 Create two private subnets with CIDR blocks 192.168.128.0/18 and 192.168.192.0/18 In the end, select Create and wait until the stack is created. At the end of the stack creation, it will give 3 outputs. SecurityGroups — this is the security group created for our VPC. SubnetIds — Ids of the 4 subnets we have created. A VpcId — Id of the VPC created. We can create clusters easily by giving eksctl create cluster command. But let’s create a YAML file with additional configurations below. In the above cluster.yaml file, we define the following configurations for our cluster. Cluster name will be EKS-Demo-Cluster In vpc section, we provide the already created VPC earlier In node group, we create 3 workers with t2.meduim instances. Out of 3 workers 2 will be created as public workers while one will be private. Now issue below command to create our cluster on EKS. eksctl create cluster -f cluster.yaml --kubeconfig=C:\Users\{user}\.kube\config After that eksctl will start creating our cluster according to our YAML file. Creating the cluster and nodes will take several minutes. At the get issue following command to check whether our cluster is deployed. kubectl get svc Sometimes you may get the following error when you issue the kubectl command. This might mean that in our kubectl config file, credentials and users required to access our cluster is not defined. error: no configuration has been provided, try setting KUBERNETES_MASTER environment variable To write these configuration details to config file issue following command. aws eks --region {region} update-kubeconfig --name EKS-Demo-Cluster Now let’s start to deploy our application on the created Kubernetes cluster. First, to deploy our application on pods, we need to create a deployment. Below is the deployment manifest that will be used for deployment. Our application label will be app:web In spec:template:spec:containers set image for the AWS ECR image we pushed Number of replicas for the application is 2 Issue following command to create our deployment. kubectl apply -f deployment.yaml To check whether our deployment created, issue below command. kubectl get deployments Now we can see that our deployment is created and is running on two pods. Now to access our application, we need to create a service. Our service type will be Nodeport because we need our application to access from outside. service type is Nodeport targetPort is 3000 since that is our container exposed port the selector will be app:web since that is the label we defined in our deployment To create our service issue below command kubectl apply -f service.yaml To check whether our service created, issue below command. kubectl get services Now let’s try to access our web application externally. From the service, we know that our application is listening on port 31479. Next, we need to acquire the public IP address of our application nodes. Let’s first try to identify where are the pods of our application are running. kubectl get pods -o wide From that, we can identify the nodes of the pods that our application is running. To get the external IP addresses of those nodes, issue the get nodes command. kubectl get nodes -o wide In the above nodes list, we can see two of our nodes have external IPs while one does not have because we configured it as a private worker node. Now we have our IP addresses as well as the port it is listening. The next task will be to add this port in the node’s security group to allow traffic in. For that identify security group created for nodes and add an inbound rule to allow traffic in port 31479. After that, we can get a public node IP address and call to it with port 31479. We can also do the same with other IP address and the result should be the same. The next task would be to deploy a database into our Kubernetes cluster. But I will leave that task for you to try out. After that make sure to delete the cluster by giving below command to avoid charges on EC2 instances we created. eksctl delete cluster --region=ap-southeast-1 --name=EKS-Demo-Cluster That is it for how to create and deploy applications to Kubernetes using AWS EKS and ECR. There are so many other concepts inside Kubernetes as well as on EKS that we can learn. So make sure to learn more and more until you feel the confidence to deploy and manage applications. Thank you.
[ { "code": null, "e": 580, "s": 172, "text": "Kubernetes is a container orchestration platform that is created by Google in 2014. It is an open-source platform where currently many organizations widely use for container deployment and management. Although there are other container orchestration tools are available in the community like Docker Swarm, Kubernetes remains in the top for container orchestration due to its features and flexible usability." }, { "code": null, "e": 923, "s": 580, "text": "Amazon Elastic Kubernetes Service is a service provided for Kubernetes on AWS infrastructure. Like any other service offered by AWS, Kubernetes resources will be fully managed by AWS themselves, which gives less overload for developers on maintaining them. AWS also make sure that these resources are highly available and reliable every time." }, { "code": null, "e": 1187, "s": 923, "text": "Amazon Elastic Container Registry is a fully managed Docker registry provided by AWS. Just like the popular docker registry Dockerhub, ECR also supports private and public repositories which are very secure. We can either push or pull images to ECR using AWS CLI." }, { "code": null, "e": 1454, "s": 1187, "text": "In this article, we are going to explore how we can deploy Kubernetes applications using AWS EKS and ECR services. Before going into complex details about how we are going to implement our Kubernetes solution below is the summary of tasks that we will be performing." }, { "code": null, "e": 1500, "s": 1454, "text": "Create a simple web application using Node.js" }, { "code": null, "e": 1545, "s": 1500, "text": "Create a docker image of the web application" }, { "code": null, "e": 1578, "s": 1545, "text": "Push our docker image to AWS ECR" }, { "code": null, "e": 1643, "s": 1578, "text": "Create a VPC with public and private subnets for our EKS Cluster" }, { "code": null, "e": 1671, "s": 1643, "text": "Create a Kubernetes Cluster" }, { "code": null, "e": 1725, "s": 1671, "text": "Create Kubernetes workers(public and private workers)" }, { "code": null, "e": 1766, "s": 1725, "text": "Deploy our web application on Kubernetes" }, { "code": null, "e": 1981, "s": 1766, "text": "Now I hope you have at least a little bit of an idea about what we are going to cover in this article. Before we start implementing we need to have the following prerequisites available in our development machines." }, { "code": null, "e": 2180, "s": 1981, "text": "Kubectl — communication tool we will use to communicate between our Kubernetes cluster and our machine. Installation instructions available on https://kubernetes.io/docs/tasks/tools/install-kubectl/" }, { "code": null, "e": 2357, "s": 2180, "text": "AWS CLI — AWS tool which we will use to issue commands related to AWS configurations. To install follow https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html" }, { "code": null, "e": 2547, "s": 2357, "text": "Aws iam authenticator — Give permission with IAM roles to access our Kubernetes cluster. For installation https://docs.aws.amazon.com/eks/latest/userguide/install-aws-iam-authenticator.html" }, { "code": null, "e": 2641, "s": 2547, "text": "eksctl — Official CLI tool for AWS EKS. For installation https://github.com/weaveworks/eksctl" }, { "code": null, "e": 2833, "s": 2641, "text": "After fulfilling our prerequisites first task will be to creating a simple server. I am using Node.js with express to create a very simple web application that will be listening on port 3000." }, { "code": null, "e": 2937, "s": 2833, "text": "Next, let’s dockerize our web application. For that create a Dockerfile and issue docker build command." }, { "code": null, "e": 2962, "s": 2937, "text": "docker build -t webapp ." }, { "code": null, "e": 3070, "s": 2962, "text": "Now if you issue docker images we will see our webapp image. The next task is to push our image to AWS ECR." }, { "code": null, "e": 3200, "s": 3070, "text": "Before we can push the image we need to create a repository on ECR. For that go to the ECR dashboard and click Create Repository." }, { "code": null, "e": 3361, "s": 3200, "text": "Now we have a repository to push our image. But before that, we need to authenticate our AWS CLI to push images to our repository. For that issue below command." }, { "code": null, "e": 3489, "s": 3361, "text": "(Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com" }, { "code": null, "e": 3651, "s": 3489, "text": "After that tag the image with our repository name. Here as the version, you can give any version, but in this instance, I am going to make the version as latest." }, { "code": null, "e": 3742, "s": 3651, "text": "docker tag webapp:latest 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com/eks-demo:latest" }, { "code": null, "e": 3799, "s": 3742, "text": "Now the last step, push our image to the ECR repository." }, { "code": null, "e": 3877, "s": 3799, "text": "docker push 628640267234.dkr.ecr.ap-southeast-1.amazonaws.com/eks-demo:latest" }, { "code": null, "e": 3991, "s": 3877, "text": "If you get any permission issues make sure your AWS CLI role has permission AmazonEC2ContainerRegistryFullAccess." }, { "code": null, "e": 4067, "s": 3991, "text": "Now go to our repository and the image we pushed should be available there." }, { "code": null, "e": 4307, "s": 4067, "text": "The next step would be to create our EKS cluster. When we create our cluster, we need to specify the VPC subnets for our cluster to use. Amazon EKS requires subnets in at least two Availability Zones. When creating VPC we have two options." }, { "code": null, "e": 4341, "s": 4307, "text": "Create public and private subnets" }, { "code": null, "e": 4368, "s": 4341, "text": "Create only public subnets" }, { "code": null, "e": 4715, "s": 4368, "text": "In this article, we are going to create a combination of public and private subnets. In that case, our web application can be externally accessed by using a public subnet, also if we need to deploy something like database then we can make them private which will be only accessible by our web application and any other application within the VPC." }, { "code": null, "e": 4902, "s": 4715, "text": "VPC for our cluster can be created manually if we want. But let’s create our VPC using AWS Cloudformation because AWS already has a template for creating a public and private subnet VPC." }, { "code": null, "e": 4957, "s": 4902, "text": "Go to CloudFormation dashboard and select Create Stack" }, { "code": null, "e": 5061, "s": 4957, "text": "Here select template source as Amazon S3 URL and provide the following template already created by AWS." }, { "code": null, "e": 5169, "s": 5061, "text": "https://amazon-eks.s3.us-west-2.amazonaws.com/cloudformation/2020-06-10/amazon-eks-vpc-private-subnets.yaml" }, { "code": null, "e": 5216, "s": 5169, "text": "VPC will have CIDR addresses of 192.168.0.0/16" }, { "code": null, "e": 5294, "s": 5216, "text": "Create two public subnets with CIDR blocks 192.168.0.0/18 and 192.168.64.0/18" }, { "code": null, "e": 5376, "s": 5294, "text": "Create two private subnets with CIDR blocks 192.168.128.0/18 and 192.168.192.0/18" }, { "code": null, "e": 5497, "s": 5376, "text": "In the end, select Create and wait until the stack is created. At the end of the stack creation, it will give 3 outputs." }, { "code": null, "e": 5562, "s": 5497, "text": "SecurityGroups — this is the security group created for our VPC." }, { "code": null, "e": 5614, "s": 5562, "text": "SubnetIds — Ids of the 4 subnets we have created. A" }, { "code": null, "e": 5645, "s": 5614, "text": "VpcId — Id of the VPC created." }, { "code": null, "e": 5783, "s": 5645, "text": "We can create clusters easily by giving eksctl create cluster command. But let’s create a YAML file with additional configurations below." }, { "code": null, "e": 5871, "s": 5783, "text": "In the above cluster.yaml file, we define the following configurations for our cluster." }, { "code": null, "e": 5909, "s": 5871, "text": "Cluster name will be EKS-Demo-Cluster" }, { "code": null, "e": 5968, "s": 5909, "text": "In vpc section, we provide the already created VPC earlier" }, { "code": null, "e": 6109, "s": 5968, "text": "In node group, we create 3 workers with t2.meduim instances. Out of 3 workers 2 will be created as public workers while one will be private." }, { "code": null, "e": 6163, "s": 6109, "text": "Now issue below command to create our cluster on EKS." }, { "code": null, "e": 6243, "s": 6163, "text": "eksctl create cluster -f cluster.yaml --kubeconfig=C:\\Users\\{user}\\.kube\\config" }, { "code": null, "e": 6456, "s": 6243, "text": "After that eksctl will start creating our cluster according to our YAML file. Creating the cluster and nodes will take several minutes. At the get issue following command to check whether our cluster is deployed." }, { "code": null, "e": 6472, "s": 6456, "text": "kubectl get svc" }, { "code": null, "e": 6668, "s": 6472, "text": "Sometimes you may get the following error when you issue the kubectl command. This might mean that in our kubectl config file, credentials and users required to access our cluster is not defined." }, { "code": null, "e": 6762, "s": 6668, "text": "error: no configuration has been provided, try setting KUBERNETES_MASTER environment variable" }, { "code": null, "e": 6839, "s": 6762, "text": "To write these configuration details to config file issue following command." }, { "code": null, "e": 6907, "s": 6839, "text": "aws eks --region {region} update-kubeconfig --name EKS-Demo-Cluster" }, { "code": null, "e": 7125, "s": 6907, "text": "Now let’s start to deploy our application on the created Kubernetes cluster. First, to deploy our application on pods, we need to create a deployment. Below is the deployment manifest that will be used for deployment." }, { "code": null, "e": 7163, "s": 7125, "text": "Our application label will be app:web" }, { "code": null, "e": 7238, "s": 7163, "text": "In spec:template:spec:containers set image for the AWS ECR image we pushed" }, { "code": null, "e": 7282, "s": 7238, "text": "Number of replicas for the application is 2" }, { "code": null, "e": 7332, "s": 7282, "text": "Issue following command to create our deployment." }, { "code": null, "e": 7365, "s": 7332, "text": "kubectl apply -f deployment.yaml" }, { "code": null, "e": 7427, "s": 7365, "text": "To check whether our deployment created, issue below command." }, { "code": null, "e": 7451, "s": 7427, "text": "kubectl get deployments" }, { "code": null, "e": 7525, "s": 7451, "text": "Now we can see that our deployment is created and is running on two pods." }, { "code": null, "e": 7675, "s": 7525, "text": "Now to access our application, we need to create a service. Our service type will be Nodeport because we need our application to access from outside." }, { "code": null, "e": 7700, "s": 7675, "text": "service type is Nodeport" }, { "code": null, "e": 7760, "s": 7700, "text": "targetPort is 3000 since that is our container exposed port" }, { "code": null, "e": 7842, "s": 7760, "text": "the selector will be app:web since that is the label we defined in our deployment" }, { "code": null, "e": 7884, "s": 7842, "text": "To create our service issue below command" }, { "code": null, "e": 7914, "s": 7884, "text": "kubectl apply -f service.yaml" }, { "code": null, "e": 7973, "s": 7914, "text": "To check whether our service created, issue below command." }, { "code": null, "e": 7994, "s": 7973, "text": "kubectl get services" }, { "code": null, "e": 8277, "s": 7994, "text": "Now let’s try to access our web application externally. From the service, we know that our application is listening on port 31479. Next, we need to acquire the public IP address of our application nodes. Let’s first try to identify where are the pods of our application are running." }, { "code": null, "e": 8302, "s": 8277, "text": "kubectl get pods -o wide" }, { "code": null, "e": 8462, "s": 8302, "text": "From that, we can identify the nodes of the pods that our application is running. To get the external IP addresses of those nodes, issue the get nodes command." }, { "code": null, "e": 8488, "s": 8462, "text": "kubectl get nodes -o wide" }, { "code": null, "e": 8896, "s": 8488, "text": "In the above nodes list, we can see two of our nodes have external IPs while one does not have because we configured it as a private worker node. Now we have our IP addresses as well as the port it is listening. The next task will be to add this port in the node’s security group to allow traffic in. For that identify security group created for nodes and add an inbound rule to allow traffic in port 31479." }, { "code": null, "e": 8976, "s": 8896, "text": "After that, we can get a public node IP address and call to it with port 31479." }, { "code": null, "e": 9057, "s": 8976, "text": "We can also do the same with other IP address and the result should be the same." }, { "code": null, "e": 9290, "s": 9057, "text": "The next task would be to deploy a database into our Kubernetes cluster. But I will leave that task for you to try out. After that make sure to delete the cluster by giving below command to avoid charges on EC2 instances we created." }, { "code": null, "e": 9360, "s": 9290, "text": "eksctl delete cluster --region=ap-southeast-1 --name=EKS-Demo-Cluster" } ]
Word2Vec Implementation. How to implement Word2Vec using numpy... | by Rahuljha | Towards Data Science
This article is about the implementation of a very popular word embedding technique known as Word2Vec. It was implemented by Tomas Mikolov at Google. Objective Introduction Core idea Architecture Data preparation Model training Model inference and analysis The objective of this article to show the inner workings of Word2Vec in python using numpy. I will not be using any other libraries for that. This implementation is not an efficient one as the purpose here is to understand the mechanism behind it. You can find the official paper here. Computers only understand the language of numbers. The way we encode our text data to numbers influences the outcome a lot. In general there are 3 techniques which are used to perform this task. Bag-of-words Tf-Idf Word2Vec Out of these, word2vec performs incredibly well in NLP tasks. The core idea behind the concept is very simple yet it produces amazing results. “A man is known by the company he keeps” ― Aesop This is a very well know saying. And word2vec also works primarily on this idea. A word is known by the company it keeps. This sounds so strange and funny but it gives amazing results. Let us try to understand it a bit more. Some sample sentences: The rewards of all your hard work in the garden are easy to see. It is hard work to keep my room in proper order. The hard work began to tell on him. Here we can easily see that the words “hard” and “work” occur in close vicinity. This seems very easy as a human being to observe, but for computers it is a very difficult task. So when we vectorize (turn words to numbers) these words, it seems obvious that there representation as numbers should be similar or close. This is exactly what word2vec achieves and with a very good result. Enough said, now time to get our hands dirty! So with the core idea understood, we understand that the algorithm is based on recognizing words in vicinity of each other. In other words we can say that if the computer tries to learn that the words “hard” and “work” occur in close proximity of each other then it will learn the vectors according to that. If we say that our “target” word is “hard” for which we need to learn a good vector, we provide the computer with its nearby word or the “context” word which is “work” in this case amongst “the, began, is etc”. There are two main architectures which try to learn the above. Skip gram and CBOW Skip-gram : So we understood about the concept of target and context words. This model, tries to learn the context words for each of the target words. Intuition: Text : ['Best way to success is through hard work and persistence'] So for this model our input will be like : Target word : Best. Context word : (way). Target word : way. Now here we have two words, one before and after. So in this scenario our context words will be : (Best,to). Target word : to. Now here also we have two words, one before and after i,e (way,success). But if we think again, then “to” and “is” can be found in sentences nearby to each other. Like “He is going to the market”. So it is a good idea if we include the word “is” in the list of context words. But now we can argue about “Best” or “through”. So here comes the concept of “window size”. Window size is the number which we decide that how many nearby words are we going to consider. So if the window size is 1 then our list of context words become (way,success). And if the window size is 2 then our list of context words become (Best,way,success,is). Similarly we can formulate the list for the rest of the words So we see here there is an input layer, a hidden layer and a output layer. We can also see there are two sets of weights (W, W`). CBOW: Context bag of words. Conceptually this is just the opposite of skip-gram. Here we try to predict the target word from a list of context words. So for our example, we will have the input as (Best,way,success,is) and we will need to predict “to” from it. We can see here it is just the opposite of skip-gram model. In this article, I will be implementing the skip-gram model. To train a model to learn good vectors for words, we will need a huge amount of data. But in this article i will try to showcase the workings on a very small data set. The data set consists of plots of various stories of Jeffery Archer taken from Wikipedia. Step 1: Read data from a file Explanation: Line 2–4 : Read contents of the text file to a list Line 7–8: Keep only the alphabets and remove everything else from each line Line 9–17: Iterate each word in the sentence and remove stopwords if specified Step 2: Generate variables We will need some variables which will come handy to us in further sections. word_to_index : A dictionary mapping each word to an integer value {‘modern’: 0, ‘humans’: 1} index_to_word : A dictionary mapping each integer value to a word {0: ‘modern’, 1: ‘humans’}corpus : The entire data consisting of all the words vocab_size : Number of unique words in the corpus Explanation: Line 10 : Convert each word to lowercase Line 12–15: Update the dictionaries with the word and there counts if the word is not already present in the dictionary The output of this code will give: text = ['Best way to success is through hardwork and persistence']Number of unique words: 9word_to_index : {'best': 0, 'way': 1, 'to': 2, 'success': 3, 'is': 4, 'through': 5, 'hardwork': 6, 'and': 7, 'persistence': 8}index_to_word : {0: 'best', 1: 'way', 2: 'to', 3: 'success', 4: 'is', 5: 'through', 6: 'hardwork', 7: 'and', 8: 'persistence'}corpus: ['best', 'way', 'to', 'success', 'is', 'through', 'hardwork', 'and', 'persistence']Length of corpus : 9 Step 3: Generate training data Before seeing the code let us first understand some concepts. One-hot-vector : Basically this is a way to encode data with 0’s and 1’s . Let us say we have a text : “ hi john”. So our one-hot-vector will be of size 2 as we have two words and we will have two separate vectors, 1 for hi and 1 for john. Example: (word: hi , one-hot-vector: [1, 0]) , (word: john , one-hot-vector: [0, 1] The following code generates one-hot-vectors for our data: Explanation: text = ['Best way to success is through hardwork and persistence']Window size = 2, Vocab size = 9We will set the indices as 1 according to the word_to_index dict i.e best : 0, so we set the 0th index as 1 to denote naturalTarget word = best Context words = (way,to)Target_word_one_hot_vector = [1, 0, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector = [0, 1, 1, 0, 0, 0, 0, 0, 0]Target word = way Context words = (best,to,success)Target_word_one_hot_vector = [0, 1, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector= [1, 0, 1, 1, 0, 0, 0, 0, 0] There is an alternate way to generate the context_word_one_hot_vector. Target word = best Context words = (way,to)Target_word_one_hot_vector = [1, 0, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector = [0, 1, 0, 0, 0, 0, 0, 0, 0],[0, 0, 1, 0, 0, 0, 0, 0, 0] Instead of having the indices present in a single list, we have two different list. But the problem with this approach is that it will take a lot of space if the size of our data increases. I have illustrated that in a python script. Refer to the code to see the difference. Now we have the vectors generated for target word and context word. To train a model, we need to have the data in the form of (X,Y) i.e (target_words, context_words). This is achieved by the following code: Explanation: text = ['Best way to success is through hardwork and persistence'] Line 7: Iterate the corpus Line 9: Set the ith word as the target word Line 14,21,27 : Condition to check if the ith word in line 9 is the (first :Best) , (middle : way) or the (last : persistence) word . Line 17 : If it is the first word, get the next 2 (window_size =2) words and set them as context words Line 21 : If it is the last word, get the previous 2 (window_size =2) words and set them as context words Line 30,37 : If our ith word is a middle word, then we need to get 2 (window_size =2) words before the ith word and 2 (window_size =2 ) words after the ith word and set all 4 as the context words. If there is only 1 word before or after the ith word, we get only 1 word. Example: **************************************************Target word:best . Target vector: [1. 0. 0. 0. 0. 0. 0. 0. 0.] Context word:['way', 'to'] .Context vector: [0. 1. 1. 0. 0. 0. 0. 0. 0.] **************************************************Target word:way . Target vector: [0. 1. 0. 0. 0. 0. 0. 0. 0.] Context word:['best', 'to', 'success'] .Context vector: [1. 0. 1. 1. 0. 0. 0. 0. 0.] **************************************************Target word:hardwork . Target vector: [0. 0. 0. 0. 0. 0. 1. 0. 0.] Context word:['through', 'is', 'and', 'persistence'] .Context vector: [0. 0. 0. 0. 1. 1. 0. 1. 1.] **************************************************Target word:and . Target vector: [0. 0. 0. 0. 0. 0. 0. 1. 0.] Context word:['hardwork', 'through', 'persistence'] . Context vector: [0. 0. 0. 0. 0. 1. 1. 0. 1.] **************************************************Target word:persistence . Target vector: [0. 0. 0. 0. 0. 0. 0. 0. 1.] Context word:['and', 'hardwork'] .Context vector: [0. 0. 0. 0. 0. 0. 1. 1. 0.] The above image shows how a neural network is trained, in this case a skip-gram model. Here we can see there is only one hidden layer. When we train a neural network in deep learning, we tend to have several hidden layers. This is where this skip-gram works so well. In spite of just having a single hidden layer it is a state-of-the-art algorithm. Forward propagation Here we have the following parameters: Input: The input we give to the model. Target words in our scenario W_1 or weight_inp_hidden : First set of weights of which is multiplied with the input to give the hidden layer. W_2 or weight_hidden_output: Second set of weight multiplied with hidden layer. Softmax layer: This is the final layer to squish the output probabilities between 0 and 1. A good explanation of the softmax function can be found here. Training error: Now once we have done 1 round of forward propagation we get some output value. So obviously we will have some error in our prediction as compared to the original value. Explanation: This is back-propagated to update the weights for the next iteration Example: below if we have 2 context words. These are not actual values.These are just for showing how the error is calculatedcontext_words = [1 0 0 1 0]y_pred = [9 6 5 4 2]So if we break the context_word vector : [1 0 0 0 0] and [0 0 0 1 0] . 1 at index 0 and 3The error should be calculated as :diff_1 = y_pred - context_word_vector_1 = [9 6 5 4 2] - [1 0 0 0 0] = [8 6 5 4 2]diff_2 = y_pred - context_word_vector_2 = [9 6 5 4 2] - [0 0 0 1 0] = [9 6 5 3 2]Total_error = diff_1 + diff_2(column_wise) = [17 12 10 7 4]Since our context vector has only 1 array , we implement the above as:index_of_1_in_context_words -> Line (6,7)A dictionary which has the index of 1's in the context_word_vector -> {0: 'yes', 3: 'yes'}number_of_1_in_context_vector -> A count for the above -> 2We loop the y_pred array and do the calculations as:for i,value in enumerate(y_p):Line(13,14) if the ith index of y_pred has a 1 in context_word_vector: total_error[i] -> i:0 . y_pred[i]:9. -> (9-1) + (1*9) ->error_calculated: 17 total_error[i] -> i:3 . y_pred[i]:4. -> (4-1) + (1*4) ->error_calculated: 7Line(15,16) else: total_error[i] -> i:1 . y_pred[i]:6. -> 6*2 ->error_calculated: 12 total_error[i] -> i:2 . y_pred[i]:5. -> 5*2 ->error_calculated: 10 total_error[i] -> i:4 . y_pred[i]:2. -> 2*2 -> error_calculated: 4total_error -> [17 12 10 7 4] Back propagation With the error calculated above we need to update the weights (W_1 and W_2) so that our network tries to rectify the error. Here is a good link that explains the derivative equations for back propagation. Finally loss calculation The loss is calculated as: If we look a bit deep into the loss function E, we see that we are trying to optimize the probability of finding correct context words p(WO,1, WO,2, · · · , WO,C) given our WI (the input word). So the loss will decrease as we come nearer to a distribution that finds the correct context words for each given target words. Explanation: The loss function is comprised of two parts. 1st part : We take a negative of the sum of the values where we have 1 for the context words2nd part : We take a exp of u , which is the output we get after multiplying the second set of weights with the hidden layer. 1st part : We take a negative of the sum of the values where we have 1 for the context words 2nd part : We take a exp of u , which is the output we get after multiplying the second set of weights with the hidden layer. u : [ 0.3831286 0.89608496 2.69426738 -1.60230182 0.45482701 0.73644591 1.10365796 1.1675781 -0.78555069]context: [0, 1, 1, 0, 0, 0, 0, 0, 0]sum_1 = -(0.89608496 + 2.69426738)sum_2 = number_of_context_words * np.log(np.sum(np.exp(u)))total_loss = sum_1 + sum_2 Hyperparameters Till now we can see that a lot of variables are involved in the process. So a very big part of training is finding the right set of variables that gives the best result. We will go by these variables one by one. Window size : This is the number of context words we are going to have for each target word.Learning rate : If we see the backward propagation code, we see that the weights are multiplied with the learning rate. This is part of the optimization process called gradient descent. A good learning rate defines how quickly our model reaches its optimum value.Epochs : Let us say we have 100 training examples. So when we do the entire process as above for each 100 records, that is counted as 1 epoch.Dimension : When our final model is ready, we get the vectors for each word. That vector can of various dimension ranging from 50 to 300.Stopwords : These are words like a , an, the. They do not have any meaning by themselves so we can check on how our model works with and without them. Window size : This is the number of context words we are going to have for each target word. Learning rate : If we see the backward propagation code, we see that the weights are multiplied with the learning rate. This is part of the optimization process called gradient descent. A good learning rate defines how quickly our model reaches its optimum value. Epochs : Let us say we have 100 training examples. So when we do the entire process as above for each 100 records, that is counted as 1 epoch. Dimension : When our final model is ready, we get the vectors for each word. That vector can of various dimension ranging from 50 to 300. Stopwords : These are words like a , an, the. They do not have any meaning by themselves so we can check on how our model works with and without them. I have done some fun experiments with window size, epochs ,dimensions ,stopwords while keeping the learning rate as 0.01 To get the word vectors for each word, after the the final training, the first set of weights i.e weight_1 is used to retrieve the vector for each word. To find the similar set of words, cosine similarity is used. It is a metric that measures how similar two vectors are in a multidimensional space. Basically it measures the angle between two vectors to find how similar they are. A good explanation of it can be found here. Now i used two different sets of data, one a single line of text and the other a text corpus. Inference with a single line of text as input Text : [‘best way to success is through hardwork and persistence’] The scatter plots show below are of 2 dimension. This is done through dimensionality reduction. I have used T-SNE for it. The figure below does not give an exact picture of as we are compressing several dimensions into 2. Scatter plot with varying dimension: We can see here that how close “best” and “way” are present. Even though a single line of text is very very scarce for a model to train, yet it learns good embedding. Scatter plot with varying window size: Inference with a relatively larger corpus To see how well the model is working, i printed a similarity matrix for some words with a larger corpus Varying dimension : One thing to observe here is that for higher dimension, the numbers for similarity is low. The reason behind this is that the corpus is very small with only around 700 unique words. So to learn embedding for a larger dimension, a huge corpus is needed. The word2vec algorithm is trained on a corpus of size in millions. Stopwords: The model seemed to perform better without stopwords as the loss curve was better for each epoch. To have a better understanding of it we need to try it on a bigger corpus. The scatter plot for above can be found at my github link here. Training of word2vec is a very computationally expensive process. With millions of word the training may take a lot of time. Some methods to counter this are negative sampling and Hierarchical softmax. A good link to understand both can be found here. The entire code can be found at my github repository : https://github.com/rahul1728jha/Word2Vec_Implementation/blob/master/Word_2_Vec.ipynb Please leave comments for any clarifications or questions. Happy learning 😃
[ { "code": null, "e": 322, "s": 172, "text": "This article is about the implementation of a very popular word embedding technique known as Word2Vec. It was implemented by Tomas Mikolov at Google." }, { "code": null, "e": 332, "s": 322, "text": "Objective" }, { "code": null, "e": 345, "s": 332, "text": "Introduction" }, { "code": null, "e": 355, "s": 345, "text": "Core idea" }, { "code": null, "e": 368, "s": 355, "text": "Architecture" }, { "code": null, "e": 385, "s": 368, "text": "Data preparation" }, { "code": null, "e": 400, "s": 385, "text": "Model training" }, { "code": null, "e": 429, "s": 400, "text": "Model inference and analysis" }, { "code": null, "e": 715, "s": 429, "text": "The objective of this article to show the inner workings of Word2Vec in python using numpy. I will not be using any other libraries for that. This implementation is not an efficient one as the purpose here is to understand the mechanism behind it. You can find the official paper here." }, { "code": null, "e": 910, "s": 715, "text": "Computers only understand the language of numbers. The way we encode our text data to numbers influences the outcome a lot. In general there are 3 techniques which are used to perform this task." }, { "code": null, "e": 923, "s": 910, "text": "Bag-of-words" }, { "code": null, "e": 930, "s": 923, "text": "Tf-Idf" }, { "code": null, "e": 939, "s": 930, "text": "Word2Vec" }, { "code": null, "e": 1082, "s": 939, "text": "Out of these, word2vec performs incredibly well in NLP tasks. The core idea behind the concept is very simple yet it produces amazing results." }, { "code": null, "e": 1123, "s": 1082, "text": "“A man is known by the company he keeps”" }, { "code": null, "e": 1131, "s": 1123, "text": "― Aesop" }, { "code": null, "e": 1356, "s": 1131, "text": "This is a very well know saying. And word2vec also works primarily on this idea. A word is known by the company it keeps. This sounds so strange and funny but it gives amazing results. Let us try to understand it a bit more." }, { "code": null, "e": 1379, "s": 1356, "text": "Some sample sentences:" }, { "code": null, "e": 1444, "s": 1379, "text": "The rewards of all your hard work in the garden are easy to see." }, { "code": null, "e": 1493, "s": 1444, "text": "It is hard work to keep my room in proper order." }, { "code": null, "e": 1529, "s": 1493, "text": "The hard work began to tell on him." }, { "code": null, "e": 1961, "s": 1529, "text": "Here we can easily see that the words “hard” and “work” occur in close vicinity. This seems very easy as a human being to observe, but for computers it is a very difficult task. So when we vectorize (turn words to numbers) these words, it seems obvious that there representation as numbers should be similar or close. This is exactly what word2vec achieves and with a very good result. Enough said, now time to get our hands dirty!" }, { "code": null, "e": 2269, "s": 1961, "text": "So with the core idea understood, we understand that the algorithm is based on recognizing words in vicinity of each other. In other words we can say that if the computer tries to learn that the words “hard” and “work” occur in close proximity of each other then it will learn the vectors according to that." }, { "code": null, "e": 2480, "s": 2269, "text": "If we say that our “target” word is “hard” for which we need to learn a good vector, we provide the computer with its nearby word or the “context” word which is “work” in this case amongst “the, began, is etc”." }, { "code": null, "e": 2562, "s": 2480, "text": "There are two main architectures which try to learn the above. Skip gram and CBOW" }, { "code": null, "e": 2713, "s": 2562, "text": "Skip-gram : So we understood about the concept of target and context words. This model, tries to learn the context words for each of the target words." }, { "code": null, "e": 2724, "s": 2713, "text": "Intuition:" }, { "code": null, "e": 2792, "s": 2724, "text": "Text : ['Best way to success is through hard work and persistence']" }, { "code": null, "e": 2835, "s": 2792, "text": "So for this model our input will be like :" }, { "code": null, "e": 2877, "s": 2835, "text": "Target word : Best. Context word : (way)." }, { "code": null, "e": 3005, "s": 2877, "text": "Target word : way. Now here we have two words, one before and after. So in this scenario our context words will be : (Best,to)." }, { "code": null, "e": 3655, "s": 3005, "text": "Target word : to. Now here also we have two words, one before and after i,e (way,success). But if we think again, then “to” and “is” can be found in sentences nearby to each other. Like “He is going to the market”. So it is a good idea if we include the word “is” in the list of context words. But now we can argue about “Best” or “through”. So here comes the concept of “window size”. Window size is the number which we decide that how many nearby words are we going to consider. So if the window size is 1 then our list of context words become (way,success). And if the window size is 2 then our list of context words become (Best,way,success,is)." }, { "code": null, "e": 3717, "s": 3655, "text": "Similarly we can formulate the list for the rest of the words" }, { "code": null, "e": 3847, "s": 3717, "text": "So we see here there is an input layer, a hidden layer and a output layer. We can also see there are two sets of weights (W, W`)." }, { "code": null, "e": 4107, "s": 3847, "text": "CBOW: Context bag of words. Conceptually this is just the opposite of skip-gram. Here we try to predict the target word from a list of context words. So for our example, we will have the input as (Best,way,success,is) and we will need to predict “to” from it." }, { "code": null, "e": 4167, "s": 4107, "text": "We can see here it is just the opposite of skip-gram model." }, { "code": null, "e": 4228, "s": 4167, "text": "In this article, I will be implementing the skip-gram model." }, { "code": null, "e": 4486, "s": 4228, "text": "To train a model to learn good vectors for words, we will need a huge amount of data. But in this article i will try to showcase the workings on a very small data set. The data set consists of plots of various stories of Jeffery Archer taken from Wikipedia." }, { "code": null, "e": 4516, "s": 4486, "text": "Step 1: Read data from a file" }, { "code": null, "e": 4529, "s": 4516, "text": "Explanation:" }, { "code": null, "e": 4581, "s": 4529, "text": "Line 2–4 : Read contents of the text file to a list" }, { "code": null, "e": 4657, "s": 4581, "text": "Line 7–8: Keep only the alphabets and remove everything else from each line" }, { "code": null, "e": 4736, "s": 4657, "text": "Line 9–17: Iterate each word in the sentence and remove stopwords if specified" }, { "code": null, "e": 4763, "s": 4736, "text": "Step 2: Generate variables" }, { "code": null, "e": 4840, "s": 4763, "text": "We will need some variables which will come handy to us in further sections." }, { "code": null, "e": 5129, "s": 4840, "text": "word_to_index : A dictionary mapping each word to an integer value {‘modern’: 0, ‘humans’: 1} index_to_word : A dictionary mapping each integer value to a word {0: ‘modern’, 1: ‘humans’}corpus : The entire data consisting of all the words vocab_size : Number of unique words in the corpus" }, { "code": null, "e": 5142, "s": 5129, "text": "Explanation:" }, { "code": null, "e": 5183, "s": 5142, "text": "Line 10 : Convert each word to lowercase" }, { "code": null, "e": 5303, "s": 5183, "text": "Line 12–15: Update the dictionaries with the word and there counts if the word is not already present in the dictionary" }, { "code": null, "e": 5338, "s": 5303, "text": "The output of this code will give:" }, { "code": null, "e": 5795, "s": 5338, "text": "text = ['Best way to success is through hardwork and persistence']Number of unique words: 9word_to_index : {'best': 0, 'way': 1, 'to': 2, 'success': 3, 'is': 4, 'through': 5, 'hardwork': 6, 'and': 7, 'persistence': 8}index_to_word : {0: 'best', 1: 'way', 2: 'to', 3: 'success', 4: 'is', 5: 'through', 6: 'hardwork', 7: 'and', 8: 'persistence'}corpus: ['best', 'way', 'to', 'success', 'is', 'through', 'hardwork', 'and', 'persistence']Length of corpus : 9" }, { "code": null, "e": 5826, "s": 5795, "text": "Step 3: Generate training data" }, { "code": null, "e": 5888, "s": 5826, "text": "Before seeing the code let us first understand some concepts." }, { "code": null, "e": 6212, "s": 5888, "text": "One-hot-vector : Basically this is a way to encode data with 0’s and 1’s . Let us say we have a text : “ hi john”. So our one-hot-vector will be of size 2 as we have two words and we will have two separate vectors, 1 for hi and 1 for john. Example: (word: hi , one-hot-vector: [1, 0]) , (word: john , one-hot-vector: [0, 1]" }, { "code": null, "e": 6271, "s": 6212, "text": "The following code generates one-hot-vectors for our data:" }, { "code": null, "e": 6284, "s": 6271, "text": "Explanation:" }, { "code": null, "e": 6833, "s": 6284, "text": "text = ['Best way to success is through hardwork and persistence']Window size = 2, Vocab size = 9We will set the indices as 1 according to the word_to_index dict i.e best : 0, so we set the 0th index as 1 to denote naturalTarget word = best Context words = (way,to)Target_word_one_hot_vector = [1, 0, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector = [0, 1, 1, 0, 0, 0, 0, 0, 0]Target word = way Context words = (best,to,success)Target_word_one_hot_vector = [0, 1, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector= [1, 0, 1, 1, 0, 0, 0, 0, 0]" }, { "code": null, "e": 6904, "s": 6833, "text": "There is an alternate way to generate the context_word_one_hot_vector." }, { "code": null, "e": 7092, "s": 6904, "text": "Target word = best Context words = (way,to)Target_word_one_hot_vector = [1, 0, 0, 0, 0, 0, 0, 0, 0]Context_word_one_hot_vector = [0, 1, 0, 0, 0, 0, 0, 0, 0],[0, 0, 1, 0, 0, 0, 0, 0, 0]" }, { "code": null, "e": 7367, "s": 7092, "text": "Instead of having the indices present in a single list, we have two different list. But the problem with this approach is that it will take a lot of space if the size of our data increases. I have illustrated that in a python script. Refer to the code to see the difference." }, { "code": null, "e": 7534, "s": 7367, "text": "Now we have the vectors generated for target word and context word. To train a model, we need to have the data in the form of (X,Y) i.e (target_words, context_words)." }, { "code": null, "e": 7574, "s": 7534, "text": "This is achieved by the following code:" }, { "code": null, "e": 7587, "s": 7574, "text": "Explanation:" }, { "code": null, "e": 7654, "s": 7587, "text": "text = ['Best way to success is through hardwork and persistence']" }, { "code": null, "e": 7681, "s": 7654, "text": "Line 7: Iterate the corpus" }, { "code": null, "e": 7725, "s": 7681, "text": "Line 9: Set the ith word as the target word" }, { "code": null, "e": 7859, "s": 7725, "text": "Line 14,21,27 : Condition to check if the ith word in line 9 is the (first :Best) , (middle : way) or the (last : persistence) word ." }, { "code": null, "e": 7962, "s": 7859, "text": "Line 17 : If it is the first word, get the next 2 (window_size =2) words and set them as context words" }, { "code": null, "e": 8068, "s": 7962, "text": "Line 21 : If it is the last word, get the previous 2 (window_size =2) words and set them as context words" }, { "code": null, "e": 8339, "s": 8068, "text": "Line 30,37 : If our ith word is a middle word, then we need to get 2 (window_size =2) words before the ith word and 2 (window_size =2 ) words after the ith word and set all 4 as the context words. If there is only 1 word before or after the ith word, we get only 1 word." }, { "code": null, "e": 8348, "s": 8339, "text": "Example:" }, { "code": null, "e": 9362, "s": 8348, "text": "**************************************************Target word:best . Target vector: [1. 0. 0. 0. 0. 0. 0. 0. 0.] Context word:['way', 'to'] .Context vector: [0. 1. 1. 0. 0. 0. 0. 0. 0.] **************************************************Target word:way . Target vector: [0. 1. 0. 0. 0. 0. 0. 0. 0.] Context word:['best', 'to', 'success'] .Context vector: [1. 0. 1. 1. 0. 0. 0. 0. 0.] **************************************************Target word:hardwork . Target vector: [0. 0. 0. 0. 0. 0. 1. 0. 0.] Context word:['through', 'is', 'and', 'persistence'] .Context vector: [0. 0. 0. 0. 1. 1. 0. 1. 1.] **************************************************Target word:and . Target vector: [0. 0. 0. 0. 0. 0. 0. 1. 0.] Context word:['hardwork', 'through', 'persistence'] . Context vector: [0. 0. 0. 0. 0. 1. 1. 0. 1.] **************************************************Target word:persistence . Target vector: [0. 0. 0. 0. 0. 0. 0. 0. 1.] Context word:['and', 'hardwork'] .Context vector: [0. 0. 0. 0. 0. 0. 1. 1. 0.]" }, { "code": null, "e": 9711, "s": 9362, "text": "The above image shows how a neural network is trained, in this case a skip-gram model. Here we can see there is only one hidden layer. When we train a neural network in deep learning, we tend to have several hidden layers. This is where this skip-gram works so well. In spite of just having a single hidden layer it is a state-of-the-art algorithm." }, { "code": null, "e": 9731, "s": 9711, "text": "Forward propagation" }, { "code": null, "e": 9770, "s": 9731, "text": "Here we have the following parameters:" }, { "code": null, "e": 9838, "s": 9770, "text": "Input: The input we give to the model. Target words in our scenario" }, { "code": null, "e": 9950, "s": 9838, "text": "W_1 or weight_inp_hidden : First set of weights of which is multiplied with the input to give the hidden layer." }, { "code": null, "e": 10030, "s": 9950, "text": "W_2 or weight_hidden_output: Second set of weight multiplied with hidden layer." }, { "code": null, "e": 10183, "s": 10030, "text": "Softmax layer: This is the final layer to squish the output probabilities between 0 and 1. A good explanation of the softmax function can be found here." }, { "code": null, "e": 10199, "s": 10183, "text": "Training error:" }, { "code": null, "e": 10368, "s": 10199, "text": "Now once we have done 1 round of forward propagation we get some output value. So obviously we will have some error in our prediction as compared to the original value." }, { "code": null, "e": 10450, "s": 10368, "text": "Explanation: This is back-propagated to update the weights for the next iteration" }, { "code": null, "e": 11827, "s": 10450, "text": "Example: below if we have 2 context words. These are not actual values.These are just for showing how the error is calculatedcontext_words = [1 0 0 1 0]y_pred = [9 6 5 4 2]So if we break the context_word vector : [1 0 0 0 0] and [0 0 0 1 0] . 1 at index 0 and 3The error should be calculated as :diff_1 = y_pred - context_word_vector_1 = [9 6 5 4 2] - [1 0 0 0 0] = [8 6 5 4 2]diff_2 = y_pred - context_word_vector_2 = [9 6 5 4 2] - [0 0 0 1 0] = [9 6 5 3 2]Total_error = diff_1 + diff_2(column_wise) = [17 12 10 7 4]Since our context vector has only 1 array , we implement the above as:index_of_1_in_context_words -> Line (6,7)A dictionary which has the index of 1's in the context_word_vector -> {0: 'yes', 3: 'yes'}number_of_1_in_context_vector -> A count for the above -> 2We loop the y_pred array and do the calculations as:for i,value in enumerate(y_p):Line(13,14) if the ith index of y_pred has a 1 in context_word_vector: total_error[i] -> i:0 . y_pred[i]:9. -> (9-1) + (1*9) ->error_calculated: 17 total_error[i] -> i:3 . y_pred[i]:4. -> (4-1) + (1*4) ->error_calculated: 7Line(15,16) else: total_error[i] -> i:1 . y_pred[i]:6. -> 6*2 ->error_calculated: 12 total_error[i] -> i:2 . y_pred[i]:5. -> 5*2 ->error_calculated: 10 total_error[i] -> i:4 . y_pred[i]:2. -> 2*2 -> error_calculated: 4total_error -> [17 12 10 7 4]" }, { "code": null, "e": 11844, "s": 11827, "text": "Back propagation" }, { "code": null, "e": 11968, "s": 11844, "text": "With the error calculated above we need to update the weights (W_1 and W_2) so that our network tries to rectify the error." }, { "code": null, "e": 12049, "s": 11968, "text": "Here is a good link that explains the derivative equations for back propagation." }, { "code": null, "e": 12074, "s": 12049, "text": "Finally loss calculation" }, { "code": null, "e": 12101, "s": 12074, "text": "The loss is calculated as:" }, { "code": null, "e": 12423, "s": 12101, "text": "If we look a bit deep into the loss function E, we see that we are trying to optimize the probability of finding correct context words p(WO,1, WO,2, · · · , WO,C) given our WI (the input word). So the loss will decrease as we come nearer to a distribution that finds the correct context words for each given target words." }, { "code": null, "e": 12436, "s": 12423, "text": "Explanation:" }, { "code": null, "e": 12481, "s": 12436, "text": "The loss function is comprised of two parts." }, { "code": null, "e": 12699, "s": 12481, "text": "1st part : We take a negative of the sum of the values where we have 1 for the context words2nd part : We take a exp of u , which is the output we get after multiplying the second set of weights with the hidden layer." }, { "code": null, "e": 12792, "s": 12699, "text": "1st part : We take a negative of the sum of the values where we have 1 for the context words" }, { "code": null, "e": 12918, "s": 12792, "text": "2nd part : We take a exp of u , which is the output we get after multiplying the second set of weights with the hidden layer." }, { "code": null, "e": 13186, "s": 12918, "text": "u : [ 0.3831286 0.89608496 2.69426738 -1.60230182 0.45482701 0.73644591 1.10365796 1.1675781 -0.78555069]context: [0, 1, 1, 0, 0, 0, 0, 0, 0]sum_1 = -(0.89608496 + 2.69426738)sum_2 = number_of_context_words * np.log(np.sum(np.exp(u)))total_loss = sum_1 + sum_2" }, { "code": null, "e": 13202, "s": 13186, "text": "Hyperparameters" }, { "code": null, "e": 13414, "s": 13202, "text": "Till now we can see that a lot of variables are involved in the process. So a very big part of training is finding the right set of variables that gives the best result. We will go by these variables one by one." }, { "code": null, "e": 14199, "s": 13414, "text": "Window size : This is the number of context words we are going to have for each target word.Learning rate : If we see the backward propagation code, we see that the weights are multiplied with the learning rate. This is part of the optimization process called gradient descent. A good learning rate defines how quickly our model reaches its optimum value.Epochs : Let us say we have 100 training examples. So when we do the entire process as above for each 100 records, that is counted as 1 epoch.Dimension : When our final model is ready, we get the vectors for each word. That vector can of various dimension ranging from 50 to 300.Stopwords : These are words like a , an, the. They do not have any meaning by themselves so we can check on how our model works with and without them." }, { "code": null, "e": 14292, "s": 14199, "text": "Window size : This is the number of context words we are going to have for each target word." }, { "code": null, "e": 14556, "s": 14292, "text": "Learning rate : If we see the backward propagation code, we see that the weights are multiplied with the learning rate. This is part of the optimization process called gradient descent. A good learning rate defines how quickly our model reaches its optimum value." }, { "code": null, "e": 14699, "s": 14556, "text": "Epochs : Let us say we have 100 training examples. So when we do the entire process as above for each 100 records, that is counted as 1 epoch." }, { "code": null, "e": 14837, "s": 14699, "text": "Dimension : When our final model is ready, we get the vectors for each word. That vector can of various dimension ranging from 50 to 300." }, { "code": null, "e": 14988, "s": 14837, "text": "Stopwords : These are words like a , an, the. They do not have any meaning by themselves so we can check on how our model works with and without them." }, { "code": null, "e": 15109, "s": 14988, "text": "I have done some fun experiments with window size, epochs ,dimensions ,stopwords while keeping the learning rate as 0.01" }, { "code": null, "e": 15262, "s": 15109, "text": "To get the word vectors for each word, after the the final training, the first set of weights i.e weight_1 is used to retrieve the vector for each word." }, { "code": null, "e": 15535, "s": 15262, "text": "To find the similar set of words, cosine similarity is used. It is a metric that measures how similar two vectors are in a multidimensional space. Basically it measures the angle between two vectors to find how similar they are. A good explanation of it can be found here." }, { "code": null, "e": 15629, "s": 15535, "text": "Now i used two different sets of data, one a single line of text and the other a text corpus." }, { "code": null, "e": 15675, "s": 15629, "text": "Inference with a single line of text as input" }, { "code": null, "e": 15742, "s": 15675, "text": "Text : [‘best way to success is through hardwork and persistence’]" }, { "code": null, "e": 15964, "s": 15742, "text": "The scatter plots show below are of 2 dimension. This is done through dimensionality reduction. I have used T-SNE for it. The figure below does not give an exact picture of as we are compressing several dimensions into 2." }, { "code": null, "e": 16001, "s": 15964, "text": "Scatter plot with varying dimension:" }, { "code": null, "e": 16168, "s": 16001, "text": "We can see here that how close “best” and “way” are present. Even though a single line of text is very very scarce for a model to train, yet it learns good embedding." }, { "code": null, "e": 16207, "s": 16168, "text": "Scatter plot with varying window size:" }, { "code": null, "e": 16249, "s": 16207, "text": "Inference with a relatively larger corpus" }, { "code": null, "e": 16353, "s": 16249, "text": "To see how well the model is working, i printed a similarity matrix for some words with a larger corpus" }, { "code": null, "e": 16373, "s": 16353, "text": "Varying dimension :" }, { "code": null, "e": 16693, "s": 16373, "text": "One thing to observe here is that for higher dimension, the numbers for similarity is low. The reason behind this is that the corpus is very small with only around 700 unique words. So to learn embedding for a larger dimension, a huge corpus is needed. The word2vec algorithm is trained on a corpus of size in millions." }, { "code": null, "e": 16704, "s": 16693, "text": "Stopwords:" }, { "code": null, "e": 16877, "s": 16704, "text": "The model seemed to perform better without stopwords as the loss curve was better for each epoch. To have a better understanding of it we need to try it on a bigger corpus." }, { "code": null, "e": 16941, "s": 16877, "text": "The scatter plot for above can be found at my github link here." }, { "code": null, "e": 17193, "s": 16941, "text": "Training of word2vec is a very computationally expensive process. With millions of word the training may take a lot of time. Some methods to counter this are negative sampling and Hierarchical softmax. A good link to understand both can be found here." }, { "code": null, "e": 17248, "s": 17193, "text": "The entire code can be found at my github repository :" }, { "code": null, "e": 17333, "s": 17248, "text": "https://github.com/rahul1728jha/Word2Vec_Implementation/blob/master/Word_2_Vec.ipynb" }, { "code": null, "e": 17392, "s": 17333, "text": "Please leave comments for any clarifications or questions." } ]
C - Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP. All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives − #define Substitutes a preprocessor macro. #include Inserts a particular header from another file. #undef Undefines a preprocessor macro. #ifdef Returns true if this macro is defined. #ifndef Returns true if this macro is not defined. #if Tests if a compile time condition is true. #else The alternative for #if. #elif #else and #if in one statement. #endif Ends preprocessor conditional. #error Prints error message on stderr. #pragma Issues special commands to the compiler, using a standardized method. Analyze the following examples to understand various directives. #define MAX_ARRAY_LENGTH 20 This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability. #include <stdio.h> #include "myheader.h" These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file. #undef FILE_SIZE #define FILE_SIZE 42 It tells the CPP to undefine existing FILE_SIZE and define it as 42. #ifndef MESSAGE #define MESSAGE "You wish!" #endif It tells the CPP to define MESSAGE only if MESSAGE isn't already defined. #ifdef DEBUG /* Your debugging statements here */ #endif It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation. ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified. __DATE__ The current date as a character literal in "MMM DD YYYY" format. __TIME__ The current time as a character literal in "HH:MM:SS" format. __FILE__ This contains the current filename as a string literal. __LINE__ This contains the current line number as a decimal constant. __STDC__ Defined as 1 when the compiler complies with the ANSI standard. Let's try the following example − #include <stdio.h> int main() { printf("File :%s\n", __FILE__ ); printf("Date :%s\n", __DATE__ ); printf("Time :%s\n", __TIME__ ); printf("Line :%d\n", __LINE__ ); printf("ANSI :%d\n", __STDC__ ); } When the above code in a file test.c is compiled and executed, it produces the following result − File :test.c Date :Jun 2 2012 Time :03:36:24 Line :8 ANSI :1 The C preprocessor offers the following operators to help create macros − A macro is normally confined to a single line. The macro continuation operator (\) is used to continue a macro that is too long for a single line. For example − #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example − #include <stdio.h> #define message_for(a, b) \ printf(#a " and " #b ": We love you!\n") int main(void) { message_for(Carole, Debra); return 0; } When the above code is compiled and executed, it produces the following result − Carole and Debra: We love you! The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example − #include <stdio.h> #define tokenpaster(n) printf ("token" #n " = %d", token##n) int main(void) { int token34 = 40; tokenpaster(34); return 0; } When the above code is compiled and executed, it produces the following result − token34 = 40 It happened so because this example results in the following actual output from the preprocessor − printf ("token34 = %d", token34); This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting. The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows − #include <stdio.h> #if !defined (MESSAGE) #define MESSAGE "You wish!" #endif int main(void) { printf("Here is the message: %s\n", MESSAGE); return 0; } When the above code is compiled and executed, it produces the following result − Here is the message: You wish! One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows − int square(int x) { return x * x; } We can rewrite above the code using a macro as follows − #define square(x) ((x) * (x)) Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example − #include <stdio.h> #define MAX(x,y) ((x) > (y) ? (x) : (y)) int main(void) { printf("Max between 20 and 10 is %d\n", MAX(10, 20)); return 0; } When the above code is compiled and executed, it produces the following result − Max between 20 and 10 is 20 Print Add Notes Bookmark this page
[ { "code": null, "e": 2385, "s": 2084, "text": "The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP." }, { "code": null, "e": 2639, "s": 2385, "text": "All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −" }, { "code": null, "e": 2647, "s": 2639, "text": "#define" }, { "code": null, "e": 2681, "s": 2647, "text": "Substitutes a preprocessor macro." }, { "code": null, "e": 2690, "s": 2681, "text": "#include" }, { "code": null, "e": 2737, "s": 2690, "text": "Inserts a particular header from another file." }, { "code": null, "e": 2744, "s": 2737, "text": "#undef" }, { "code": null, "e": 2776, "s": 2744, "text": "Undefines a preprocessor macro." }, { "code": null, "e": 2783, "s": 2776, "text": "#ifdef" }, { "code": null, "e": 2822, "s": 2783, "text": "Returns true if this macro is defined." }, { "code": null, "e": 2830, "s": 2822, "text": "#ifndef" }, { "code": null, "e": 2873, "s": 2830, "text": "Returns true if this macro is not defined." }, { "code": null, "e": 2877, "s": 2873, "text": "#if" }, { "code": null, "e": 2920, "s": 2877, "text": "Tests if a compile time condition is true." }, { "code": null, "e": 2926, "s": 2920, "text": "#else" }, { "code": null, "e": 2951, "s": 2926, "text": "The alternative for #if." }, { "code": null, "e": 2957, "s": 2951, "text": "#elif" }, { "code": null, "e": 2989, "s": 2957, "text": "#else and #if in one statement." }, { "code": null, "e": 2996, "s": 2989, "text": "#endif" }, { "code": null, "e": 3027, "s": 2996, "text": "Ends preprocessor conditional." }, { "code": null, "e": 3034, "s": 3027, "text": "#error" }, { "code": null, "e": 3066, "s": 3034, "text": "Prints error message on stderr." }, { "code": null, "e": 3074, "s": 3066, "text": "#pragma" }, { "code": null, "e": 3144, "s": 3074, "text": "Issues special commands to the compiler, using a standardized method." }, { "code": null, "e": 3209, "s": 3144, "text": "Analyze the following examples to understand various directives." }, { "code": null, "e": 3238, "s": 3209, "text": "#define MAX_ARRAY_LENGTH 20\n" }, { "code": null, "e": 3368, "s": 3238, "text": "This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability." }, { "code": null, "e": 3409, "s": 3368, "text": "#include <stdio.h>\n#include \"myheader.h\"" }, { "code": null, "e": 3636, "s": 3409, "text": "These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file." }, { "code": null, "e": 3675, "s": 3636, "text": "#undef FILE_SIZE\n#define FILE_SIZE 42" }, { "code": null, "e": 3744, "s": 3675, "text": "It tells the CPP to undefine existing FILE_SIZE and define it as 42." }, { "code": null, "e": 3798, "s": 3744, "text": "#ifndef MESSAGE\n #define MESSAGE \"You wish!\"\n#endif" }, { "code": null, "e": 3872, "s": 3798, "text": "It tells the CPP to define MESSAGE only if MESSAGE isn't already defined." }, { "code": null, "e": 3932, "s": 3872, "text": "#ifdef DEBUG\n /* Your debugging statements here */\n#endif" }, { "code": null, "e": 4189, "s": 3932, "text": "It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation." }, { "code": null, "e": 4334, "s": 4189, "text": "ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified." }, { "code": null, "e": 4343, "s": 4334, "text": "__DATE__" }, { "code": null, "e": 4408, "s": 4343, "text": "The current date as a character literal in \"MMM DD YYYY\" format." }, { "code": null, "e": 4417, "s": 4408, "text": "__TIME__" }, { "code": null, "e": 4479, "s": 4417, "text": "The current time as a character literal in \"HH:MM:SS\" format." }, { "code": null, "e": 4488, "s": 4479, "text": "__FILE__" }, { "code": null, "e": 4544, "s": 4488, "text": "This contains the current filename as a string literal." }, { "code": null, "e": 4553, "s": 4544, "text": "__LINE__" }, { "code": null, "e": 4614, "s": 4553, "text": "This contains the current line number as a decimal constant." }, { "code": null, "e": 4623, "s": 4614, "text": "__STDC__" }, { "code": null, "e": 4687, "s": 4623, "text": "Defined as 1 when the compiler complies with the ANSI standard." }, { "code": null, "e": 4721, "s": 4687, "text": "Let's try the following example −" }, { "code": null, "e": 4938, "s": 4721, "text": "#include <stdio.h>\n\nint main() {\n\n printf(\"File :%s\\n\", __FILE__ );\n printf(\"Date :%s\\n\", __DATE__ );\n printf(\"Time :%s\\n\", __TIME__ );\n printf(\"Line :%d\\n\", __LINE__ );\n printf(\"ANSI :%d\\n\", __STDC__ );\n\n}" }, { "code": null, "e": 5036, "s": 4938, "text": "When the above code in a file test.c is compiled and executed, it produces the following result −" }, { "code": null, "e": 5098, "s": 5036, "text": "File :test.c\nDate :Jun 2 2012\nTime :03:36:24\nLine :8\nANSI :1\n" }, { "code": null, "e": 5172, "s": 5098, "text": "The C preprocessor offers the following operators to help create macros −" }, { "code": null, "e": 5333, "s": 5172, "text": "A macro is normally confined to a single line. The macro continuation operator (\\) is used to continue a macro that is too long for a single line. For example −" }, { "code": null, "e": 5407, "s": 5333, "text": "#define message_for(a, b) \\\n printf(#a \" and \" #b \": We love you!\\n\")" }, { "code": null, "e": 5645, "s": 5407, "text": "The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example −" }, { "code": null, "e": 5803, "s": 5645, "text": "#include <stdio.h>\n\n#define message_for(a, b) \\\n printf(#a \" and \" #b \": We love you!\\n\")\n\nint main(void) {\n message_for(Carole, Debra);\n return 0;\n}" }, { "code": null, "e": 5884, "s": 5803, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5916, "s": 5884, "text": "Carole and Debra: We love you!\n" }, { "code": null, "e": 6101, "s": 5916, "text": "The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example −" }, { "code": null, "e": 6256, "s": 6101, "text": "#include <stdio.h>\n\n#define tokenpaster(n) printf (\"token\" #n \" = %d\", token##n)\n\nint main(void) {\n int token34 = 40;\n tokenpaster(34);\n return 0;\n}" }, { "code": null, "e": 6337, "s": 6256, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6351, "s": 6337, "text": "token34 = 40\n" }, { "code": null, "e": 6450, "s": 6351, "text": "It happened so because this example results in the following actual output from the preprocessor −" }, { "code": null, "e": 6484, "s": 6450, "text": "printf (\"token34 = %d\", token34);" }, { "code": null, "e": 6602, "s": 6484, "text": "This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting." }, { "code": null, "e": 6898, "s": 6602, "text": "The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows −" }, { "code": null, "e": 7063, "s": 6898, "text": "#include <stdio.h>\n\n#if !defined (MESSAGE)\n #define MESSAGE \"You wish!\"\n#endif\n\nint main(void) {\n printf(\"Here is the message: %s\\n\", MESSAGE); \n return 0;\n}" }, { "code": null, "e": 7144, "s": 7063, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 7176, "s": 7144, "text": "Here is the message: You wish!\n" }, { "code": null, "e": 7351, "s": 7176, "text": "One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows −" }, { "code": null, "e": 7390, "s": 7351, "text": "int square(int x) {\n return x * x;\n}" }, { "code": null, "e": 7447, "s": 7390, "text": "We can rewrite above the code using a macro as follows −" }, { "code": null, "e": 7477, "s": 7447, "text": "#define square(x) ((x) * (x))" }, { "code": null, "e": 7739, "s": 7477, "text": "Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example −" }, { "code": null, "e": 7892, "s": 7739, "text": "#include <stdio.h>\n\n#define MAX(x,y) ((x) > (y) ? (x) : (y))\n\nint main(void) {\n printf(\"Max between 20 and 10 is %d\\n\", MAX(10, 20)); \n return 0;\n}" }, { "code": null, "e": 7973, "s": 7892, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8002, "s": 7973, "text": "Max between 20 and 10 is 20\n" }, { "code": null, "e": 8009, "s": 8002, "text": " Print" }, { "code": null, "e": 8020, "s": 8009, "text": " Add Notes" } ]
Part 3: Time Series Chains. A New Approach to Time Series... | by Sean Law | Towards Data Science
STUMPY is a powerful and scalable Python library for modern time series analysis and, at its core, efficiently computes something called a matrix profile. The goal of this multi-part series is to explain what the matrix profile is and how you can start leveraging STUMPY for all of your modern time series data mining tasks! Note: These tutorials were originally featured in the STUMPY documentation. Part 1: The Matrix ProfilePart 2: STUMPY BasicsPart 3: Time Series ChainsPart 4: Semantic SegmentationPart 5: Fast Approximate Matrix Profiles with STUMPYPart 6: Matrix Profiles for Streaming Time Series DataPart 7: Fast Pattern Searching with STUMPYPart 8: AB-Joins with STUMPYPart 9: Time Series Consensus MotifsPart 10: Discovering Multidimensional Time Series Motifs Previously, we learned about what a matrix profile is and how to use STUMPY to discover motifs (patterns) and discords (anomalies) in any time series data. In this blog, we’ll take these concepts a step even further and explore something that is derived from a matrix profile called Time Series Chains. This example is adapted from the Web Query Volume case study and utilizes the main takeaways from the Matrix Profile VII research paper. Let’s import the packages that we’ll need to load, analyze, and plot the data. %matplotlib inlineimport pandas as pdimport numpy as npimport stumpyfrom scipy.io import loadmatimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle, FancyArrowPatchimport itertoolsplt.rcParams["figure.figsize"] = [20, 6] # width, heightplt.rcParams['xtick.direction'] = 'out' Time series chains may be informally considered as motifs that evolve or drift in some direction over time. The figure below illustrates the difference between time series motifs (left) and time series chains (right). x = np.random.rand(20)y = np.random.rand(20)n = 10motifs_x = 0.5 * np.ones(n) + np.random.uniform(-0.05, 0.05, n)motifs_y = 0.5 * np.ones(n) + np.random.uniform(-0.05, 0.05, n)sin_x = np.linspace(0, np.pi/2, n+1)sin_y = np.sin(sin_x)/4chains_x = 0.5 * np.ones(n+1) + 0.02 * np.arange(n+1)chains_y = 0.5 * np.ones(n+1) + sin_yfig, axes = plt.subplots(nrows=1, ncols=2)axes[0].scatter(x, y, color='lightgrey')axes[0].scatter(motifs_x, motifs_y, color='red')axes[1].scatter(x, y, color='lightgrey')axes[1].scatter(chains_x[0], chains_y[0], edgecolor='red', color='white')axes[1].scatter(chains_x[1:n], chains_y[1:n], color='red')axes[1].scatter(chains_x[n], chains_y[n], edgecolor='red', color='white', marker='*', s=200) Above, we are visualizing time series subsequences as points in high-dimensional space. Shown on the left is a time series motif and it can be thought of as a collection of points that approximate a platonic ideal. In contrast, depicted on the right, is a time series chain and it may be thought of as an evolving trail of points in the space. Here, the open red circle represents the first link in the chain, the anchor. Both motifs and chains have the property that each subsequence is relatively close to its nearest neighbor. However, the motif set (left) also has a relatively small diameter. In contrast, the set of points in a chain (right) has a diameter that is much larger than the mean of each member’s distance to its nearest neighbor and, moreover, the chain has the important property of directionality. For example, in the case of a motif, if an additional member was added to the motif set, its location will also be somewhere near the platonic ideal, but independent of the previous subsequences. In contrast, in the case of a chain, the location of the next member of the chain would be somewhere after the last red circle, possibly where the open red star is located. Adapted from the Matrix Profile VII paper, consider the following time series: 47, 32, 1, 22, 2, 58, 3, 36, 4, -5, 5, 40 Assume that the subsequence length is 1 and that the distance between two subsequences is simply the absolute difference between them. To be clear, we are making these simple and pathological assumptions here just for the purposes of elucidation; we are actually targeting much longer subsequence lengths and using z-normalized Euclidean distance in our STUMPY applications. To capture the directionality of a time series chain, we need to store the left and right nearest neighbor information into the left (IL) and right (IR) matrix profile indices: Index Value Left Index (IL) Right Index (IR)1 47 N/A 122 32 1 83 1 2 54 22 2 85 2 3 76 58 1 127 3 5 98 36 2 129 4 7 1110 –5 3 1111 5 9 1212 40 8 N/A In this vertical/transposed representation, the index column shows the location of every subsequence in the time series, the value column contains the original numbers from our time series above, the IL column shows the left matrix profile indices, and IR is the right matrix profile indices. For example, IR[2] = 8 means the right nearest neighbor of index = 2 (which has value = 32) is at index = 8 (which has value = 36). Similarly, IL[3] = 2 means that the left nearest neighbor of index = 3 (with value = 1) is at index = 2 (which has value = 32). To better visualize the left/right matrix profile index, we use arrows to link every subsequence in the time series with its left and right nearest neighbors: nearest_neighbors = np.array([[1, 47, np.nan, 12], [2, 32, 1, 8], [3, 1, 2, 5], [4, 22, 2, 8], [5, 2, 3, 7], [6, 58, 1, 12], [7, 3, 5, 9], [8, 36, 2, 12], [9, 4, 7, 11], [10, -5, 3, 11], [11, 5, 9, 12], [12, 40, 8, np.nan]])colors = [['C1', 'C1'], ['C2', 'C5'], ['C3', 'C5'], ['C4', 'C4'], ['C3', 'C2'], ['C5', 'C3'], ['C3', 'C2'], ['C2', 'C1'], ['C3', 'C2'], ['C6', 'C1'], ['C6', 'C2'], ['C1', 'C1']]style="Simple, tail_width=0.5, head_width=6, head_length=8"kw = dict(arrowstyle=style, connectionstyle="arc3, rad=-.5",)xs = np.arange(nearest_neighbors.shape[0]) + 1ys = np.zeros(nearest_neighbors.shape[0])plt.plot(xs, ys, "-o", markerfacecolor="None", markeredgecolor="None", linestyle="None")x0, x1, y0, y1 = plt.axis()plot_margin = 5.0plt.axis((x0 - plot_margin, x1 + plot_margin, y0 - plot_margin, y1 + plot_margin))plt.axis('off')for x, y, nearest_neighbor, color in zip(xs, ys, nearest_neighbors, colors): plt.text(x, y, str(int(nearest_neighbor[1])), color="black", fontsize=20) # Plot right matrix profile indices if not np.isnan(nearest_neighbor[3]): arrow = FancyArrowPatch((x, 0.5), (nearest_neighbor[3], 0.5), color=color[0], **kw) plt.gca().add_patch(arrow) # Plot left matrix profile indices if not np.isnan(nearest_neighbor[2]): arrow = FancyArrowPatch((x, 0.0), (nearest_neighbor[2], 0.0), color=color[1], **kw) plt.gca().add_patch(arrow) An arrow pointing from a number to its right nearest neighbor (arrows shown above the time series) can be referred to as forward arrow and an arrow pointing from a number to its left nearest neighbor (arrows shown below the time series) can be referred to as a backward arrow. According to the formal definition of a time series chain (see Matrix Profile VII for a thorough definition and discussion), every pair of consecutive subsequences in a chain must be connected by both a forward arrow and a backward arrow. A keen eye will spot the fact that the longest chain in our simplified example is: nearest_neighbors = np.array([[1, 47, np.nan, np.nan], [2, 32, np.nan, np.nan], [3, 1, np.nan, 5], [4, 22, np.nan, np.nan], [5, 2, 3, 7], [6, 58, np.nan, np.nan], [7, 3, 5, 9], [8, 36, np.nan, np.nan], [9, 4, 7, 11], [10, -5, np.nan, np.nan], [11, 5, 9, np.nan], [12, 40, np.nan, np.nan]])colors = [['C1', 'C1'], ['C2', 'C5'], ['C3', 'C5'], ['C4', 'C4'], ['C3', 'C2'], ['C5', 'C3'], ['C3', 'C2'], ['C2', 'C1'], ['C3', 'C2'], ['C6', 'C1'], ['C6', 'C2'], ['C1', 'C1']]style="Simple, tail_width=0.5, head_width=6, head_length=8"kw = dict(arrowstyle=style, connectionstyle="arc3, rad=-.5",)xs = np.arange(nearest_neighbors.shape[0]) + 1ys = np.zeros(nearest_neighbors.shape[0])plt.plot(xs, ys, "-o", markerfacecolor="None", markeredgecolor="None", linestyle="None")x0, x1, y0, y1 = plt.axis()plot_margin = 5.0plt.axis((x0 - plot_margin, x1 + plot_margin, y0 - plot_margin, y1 + plot_margin))plt.axis('off')for x, y, nearest_neighbor, color in zip(xs, ys, nearest_neighbors, colors): plt.text(x, y, str(int(nearest_neighbor[1])), color="black", fontsize=20) # Plot right matrix profile indices if not np.isnan(nearest_neighbor[3]): arrow = FancyArrowPatch((x, 0.5), (nearest_neighbor[3], 0.5), color=color[0], **kw) plt.gca().add_patch(arrow) # Plot left matrix profile indices if not np.isnan(nearest_neighbor[2]): arrow = FancyArrowPatch((x, 0.0), (nearest_neighbor[2], 0.0), color=color[1], **kw) plt.gca().add_patch(arrow) The longest extracted chain is therefore 1 ⇌ 2 ⇌ 3 ⇌ 4 ⇌ 5. Note that we see a gradual monotonic increase in the data but, in reality, the increase or decrease in drift can happen in arbitrarily complex ways that can be detected by the time series chains approach. The key component of drifting is that the time series must contain chains with clear directionality. STUMPY is capable of computing: anchored time series chains (ATSC) — grow a chain from a user-specified anchor (i.e., specific subsequence)all-chain set (ALLC) — a set of anchored time series chains (i.e., each chain starts with a particular subsequence) that are not subsumed by another longer chainunanchored time series chain(s) — the unconditionally longest chain within a time series (there could be more than one if there were chains with the same length) anchored time series chains (ATSC) — grow a chain from a user-specified anchor (i.e., specific subsequence) all-chain set (ALLC) — a set of anchored time series chains (i.e., each chain starts with a particular subsequence) that are not subsumed by another longer chain unanchored time series chain(s) — the unconditionally longest chain within a time series (there could be more than one if there were chains with the same length) So, what does this mean in the context of a real time series? Let’s take a look at a real example from web query data! We will be looking at a noisy dataset that is under-sampled and has a growing trend, which will perfectly illustrate the idea regarding time series chains. The data contains a decade-long GoogleTrend query volume (collected weekly from 2004–2014) for the keyword Kohl’s, an American retail chain. First, we’ll download the data, extract it, and insert it into a Pandas dataframe. df = pd.read_csv("https://zenodo.org/record/4276348/files/Time_Series_Chains_Kohls_data.csv?download=1")df.head() volume0 0.0104171 0.0104172 0.0104173 0.0000004 0.000000 plt.plot(df['volume'], color='black')plt.xlim(0, df.shape[0]+12)color = itertools.cycle(['white', 'gainsboro'])for i, x in enumerate(range(0, df.shape[0], 52)): plt.text(x+12, 0.9, str(2004+i), color="black", fontsize=20) rect = Rectangle((x, -1), 52, 2.5, facecolor=next(color)) plt.gca().add_patch(rect) The raw time series above displays ten years of web query volume for the keyword “Kohl’s”, where each alternating white and grey vertical band represents a 52 week period starting from 2004 to 2014. As depicted, the time series features a significant but unsurprising “end-of-year holiday bump”. Relating back to time series chains, we can see that the bump is generally increasing over time and so we might be able to capture this when we compute the unanchored chain. However, as we learned above, in order to compute any time series chains, we also need the left and right matrix profile indices. Luckily for us, according to the STUMPY documentation, the stumpy.stump() function not only returns the (bidirectional) matrix profile and the matrix profile indices in the first and second columns of the NumPy array, respectively, but the third and fourth columns consists of the left matrix profile indices and the right matrix profile indices, respectively. So, let’s go ahead and compute the matrix profile indices and we’ll set the window size, m = 20, which is the approximate length of a “bump”. m = 20mp = stumpy.stump(df['volume'], m=m) Now, with our left and right matrix profile indices in hand, we are ready to call the all-chain set STUMPY function, stumpy.allc(), which not only returns the all-chain set but, as a byproduct, it also returns the unconditionally longest chain, also know as the unanchored chain. The latter of which is really what we’re most interested in. all_chain_set, unanchored_chain = stumpy.allc(mp[:, 2], mp[:, 3]) plt.plot(df['volume'], linewidth=1, color='black')for i in range(unanchored_chain.shape[0]): y = df['volume'].iloc[unanchored_chain[i]:unanchored_chain[i]+m] x = y.index.values plt.plot(x, y, linewidth=3)color = itertools.cycle(['white', 'gainsboro'])for i, x in enumerate(range(0, df.shape[0], 52)): plt.text(x+12, 0.9, str(2004+i), color="black", fontsize=20) rect = Rectangle((x, -1), 52, 2.5, facecolor=next(color)) plt.gca().add_patch(rect) plt.axis('off')for i in range(unanchored_chain.shape[0]): data = df['volume'].iloc[unanchored_chain[i]:unanchored_chain[i]+m].reset_index().values x = data[:, 0] y = data[:, 1] plt.axvline(x=x[0]-x.min()+(m+5)*i + 11, alpha=0.3) plt.axvline(x=x[0]-x.min()+(m+5)*i + 15, alpha=0.3, linestyle='-.') plt.plot(x-x.min()+(m+5)*i, y-y.min(), linewidth=3) The discovered chain shows that over the decade, the bump transitions from a smooth bump covering the period between Thanksgiving (solid vertical line) and Christmas (dashed vertical line), to a more sharply focused bump centered on Thanksgiving. This seems to reflect the growing importance of “Cyber Monday”, a marketing term for the Monday after Thanksgiving. The phrase was created by marketing companies to persuade consumers to shop online. The term made its debut on November 28th, 2005 in a press release entitled “Cyber Monday Quickly Becoming One of the Biggest Online Shopping Days of the Year”. Note that this date coincides with the first glimpse of the sharpening peak in our chain. It also appears that we may have “missed” a few links in the chain. However, note that the data is noisy and under-sampled, and the “missed” bumps are too distorted to conform with the general evolving trend. This noisy example actually illustrates the robustness of the time series chains technique. As noted before, we don’t actually need “perfect” data in order to find meaningful chains. Even if some links are badly distorted, the discovered chain will still be able to include all of the other evolving patterns. One final consideration is the potential use of chains to predict or forecast the future. One could leverage the evolving links within the chains in order to forecast the shape of the next bump. We refer the reader to the Matrix Profile VII for further discussions on this topic. And that’s it! You’ve just learned the basics of how to identify directional trends, also known as chains, within your data using the matrix profile indices and leveraging stumpy.allc() function. Matrix Profile VII Matrix Profile VII Supplementary Materials STUMPY Matrix Profile Documentation STUMPY Matrix Profile Github Code Repository
[ { "code": null, "e": 497, "s": 172, "text": "STUMPY is a powerful and scalable Python library for modern time series analysis and, at its core, efficiently computes something called a matrix profile. The goal of this multi-part series is to explain what the matrix profile is and how you can start leveraging STUMPY for all of your modern time series data mining tasks!" }, { "code": null, "e": 573, "s": 497, "text": "Note: These tutorials were originally featured in the STUMPY documentation." }, { "code": null, "e": 944, "s": 573, "text": "Part 1: The Matrix ProfilePart 2: STUMPY BasicsPart 3: Time Series ChainsPart 4: Semantic SegmentationPart 5: Fast Approximate Matrix Profiles with STUMPYPart 6: Matrix Profiles for Streaming Time Series DataPart 7: Fast Pattern Searching with STUMPYPart 8: AB-Joins with STUMPYPart 9: Time Series Consensus MotifsPart 10: Discovering Multidimensional Time Series Motifs" }, { "code": null, "e": 1384, "s": 944, "text": "Previously, we learned about what a matrix profile is and how to use STUMPY to discover motifs (patterns) and discords (anomalies) in any time series data. In this blog, we’ll take these concepts a step even further and explore something that is derived from a matrix profile called Time Series Chains. This example is adapted from the Web Query Volume case study and utilizes the main takeaways from the Matrix Profile VII research paper." }, { "code": null, "e": 1463, "s": 1384, "text": "Let’s import the packages that we’ll need to load, analyze, and plot the data." }, { "code": null, "e": 1760, "s": 1463, "text": "%matplotlib inlineimport pandas as pdimport numpy as npimport stumpyfrom scipy.io import loadmatimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle, FancyArrowPatchimport itertoolsplt.rcParams[\"figure.figsize\"] = [20, 6] # width, heightplt.rcParams['xtick.direction'] = 'out'" }, { "code": null, "e": 1978, "s": 1760, "text": "Time series chains may be informally considered as motifs that evolve or drift in some direction over time. The figure below illustrates the difference between time series motifs (left) and time series chains (right)." }, { "code": null, "e": 2697, "s": 1978, "text": "x = np.random.rand(20)y = np.random.rand(20)n = 10motifs_x = 0.5 * np.ones(n) + np.random.uniform(-0.05, 0.05, n)motifs_y = 0.5 * np.ones(n) + np.random.uniform(-0.05, 0.05, n)sin_x = np.linspace(0, np.pi/2, n+1)sin_y = np.sin(sin_x)/4chains_x = 0.5 * np.ones(n+1) + 0.02 * np.arange(n+1)chains_y = 0.5 * np.ones(n+1) + sin_yfig, axes = plt.subplots(nrows=1, ncols=2)axes[0].scatter(x, y, color='lightgrey')axes[0].scatter(motifs_x, motifs_y, color='red')axes[1].scatter(x, y, color='lightgrey')axes[1].scatter(chains_x[0], chains_y[0], edgecolor='red', color='white')axes[1].scatter(chains_x[1:n], chains_y[1:n], color='red')axes[1].scatter(chains_x[n], chains_y[n], edgecolor='red', color='white', marker='*', s=200)" }, { "code": null, "e": 3884, "s": 2697, "text": "Above, we are visualizing time series subsequences as points in high-dimensional space. Shown on the left is a time series motif and it can be thought of as a collection of points that approximate a platonic ideal. In contrast, depicted on the right, is a time series chain and it may be thought of as an evolving trail of points in the space. Here, the open red circle represents the first link in the chain, the anchor. Both motifs and chains have the property that each subsequence is relatively close to its nearest neighbor. However, the motif set (left) also has a relatively small diameter. In contrast, the set of points in a chain (right) has a diameter that is much larger than the mean of each member’s distance to its nearest neighbor and, moreover, the chain has the important property of directionality. For example, in the case of a motif, if an additional member was added to the motif set, its location will also be somewhere near the platonic ideal, but independent of the previous subsequences. In contrast, in the case of a chain, the location of the next member of the chain would be somewhere after the last red circle, possibly where the open red star is located." }, { "code": null, "e": 3963, "s": 3884, "text": "Adapted from the Matrix Profile VII paper, consider the following time series:" }, { "code": null, "e": 4005, "s": 3963, "text": "47, 32, 1, 22, 2, 58, 3, 36, 4, -5, 5, 40" }, { "code": null, "e": 4557, "s": 4005, "text": "Assume that the subsequence length is 1 and that the distance between two subsequences is simply the absolute difference between them. To be clear, we are making these simple and pathological assumptions here just for the purposes of elucidation; we are actually targeting much longer subsequence lengths and using z-normalized Euclidean distance in our STUMPY applications. To capture the directionality of a time series chain, we need to store the left and right nearest neighbor information into the left (IL) and right (IR) matrix profile indices:" }, { "code": null, "e": 5169, "s": 4557, "text": "Index Value Left Index (IL) Right Index (IR)1 47 N/A 122 32 1 83 1 2 54 22 2 85 2 3 76 58 1 127 3 5 98 36 2 129 4 7 1110 –5 3 1111 5 9 1212 40 8 N/A" }, { "code": null, "e": 5881, "s": 5169, "text": "In this vertical/transposed representation, the index column shows the location of every subsequence in the time series, the value column contains the original numbers from our time series above, the IL column shows the left matrix profile indices, and IR is the right matrix profile indices. For example, IR[2] = 8 means the right nearest neighbor of index = 2 (which has value = 32) is at index = 8 (which has value = 36). Similarly, IL[3] = 2 means that the left nearest neighbor of index = 3 (with value = 1) is at index = 2 (which has value = 32). To better visualize the left/right matrix profile index, we use arrows to link every subsequence in the time series with its left and right nearest neighbors:" }, { "code": null, "e": 7844, "s": 5881, "text": "nearest_neighbors = np.array([[1, 47, np.nan, 12], [2, 32, 1, 8], [3, 1, 2, 5], [4, 22, 2, 8], [5, 2, 3, 7], [6, 58, 1, 12], [7, 3, 5, 9], [8, 36, 2, 12], [9, 4, 7, 11], [10, -5, 3, 11], [11, 5, 9, 12], [12, 40, 8, np.nan]])colors = [['C1', 'C1'], ['C2', 'C5'], ['C3', 'C5'], ['C4', 'C4'], ['C3', 'C2'], ['C5', 'C3'], ['C3', 'C2'], ['C2', 'C1'], ['C3', 'C2'], ['C6', 'C1'], ['C6', 'C2'], ['C1', 'C1']]style=\"Simple, tail_width=0.5, head_width=6, head_length=8\"kw = dict(arrowstyle=style, connectionstyle=\"arc3, rad=-.5\",)xs = np.arange(nearest_neighbors.shape[0]) + 1ys = np.zeros(nearest_neighbors.shape[0])plt.plot(xs, ys, \"-o\", markerfacecolor=\"None\", markeredgecolor=\"None\", linestyle=\"None\")x0, x1, y0, y1 = plt.axis()plot_margin = 5.0plt.axis((x0 - plot_margin, x1 + plot_margin, y0 - plot_margin, y1 + plot_margin))plt.axis('off')for x, y, nearest_neighbor, color in zip(xs, ys, nearest_neighbors, colors): plt.text(x, y, str(int(nearest_neighbor[1])), color=\"black\", fontsize=20) # Plot right matrix profile indices if not np.isnan(nearest_neighbor[3]): arrow = FancyArrowPatch((x, 0.5), (nearest_neighbor[3], 0.5), color=color[0], **kw) plt.gca().add_patch(arrow) # Plot left matrix profile indices if not np.isnan(nearest_neighbor[2]): arrow = FancyArrowPatch((x, 0.0), (nearest_neighbor[2], 0.0), color=color[1], **kw) plt.gca().add_patch(arrow)" }, { "code": null, "e": 8443, "s": 7844, "text": "An arrow pointing from a number to its right nearest neighbor (arrows shown above the time series) can be referred to as forward arrow and an arrow pointing from a number to its left nearest neighbor (arrows shown below the time series) can be referred to as a backward arrow. According to the formal definition of a time series chain (see Matrix Profile VII for a thorough definition and discussion), every pair of consecutive subsequences in a chain must be connected by both a forward arrow and a backward arrow. A keen eye will spot the fact that the longest chain in our simplified example is:" }, { "code": null, "e": 10406, "s": 8443, "text": "nearest_neighbors = np.array([[1, 47, np.nan, np.nan], [2, 32, np.nan, np.nan], [3, 1, np.nan, 5], [4, 22, np.nan, np.nan], [5, 2, 3, 7], [6, 58, np.nan, np.nan], [7, 3, 5, 9], [8, 36, np.nan, np.nan], [9, 4, 7, 11], [10, -5, np.nan, np.nan], [11, 5, 9, np.nan], [12, 40, np.nan, np.nan]])colors = [['C1', 'C1'], ['C2', 'C5'], ['C3', 'C5'], ['C4', 'C4'], ['C3', 'C2'], ['C5', 'C3'], ['C3', 'C2'], ['C2', 'C1'], ['C3', 'C2'], ['C6', 'C1'], ['C6', 'C2'], ['C1', 'C1']]style=\"Simple, tail_width=0.5, head_width=6, head_length=8\"kw = dict(arrowstyle=style, connectionstyle=\"arc3, rad=-.5\",)xs = np.arange(nearest_neighbors.shape[0]) + 1ys = np.zeros(nearest_neighbors.shape[0])plt.plot(xs, ys, \"-o\", markerfacecolor=\"None\", markeredgecolor=\"None\", linestyle=\"None\")x0, x1, y0, y1 = plt.axis()plot_margin = 5.0plt.axis((x0 - plot_margin, x1 + plot_margin, y0 - plot_margin, y1 + plot_margin))plt.axis('off')for x, y, nearest_neighbor, color in zip(xs, ys, nearest_neighbors, colors): plt.text(x, y, str(int(nearest_neighbor[1])), color=\"black\", fontsize=20) # Plot right matrix profile indices if not np.isnan(nearest_neighbor[3]): arrow = FancyArrowPatch((x, 0.5), (nearest_neighbor[3], 0.5), color=color[0], **kw) plt.gca().add_patch(arrow) # Plot left matrix profile indices if not np.isnan(nearest_neighbor[2]): arrow = FancyArrowPatch((x, 0.0), (nearest_neighbor[2], 0.0), color=color[1], **kw) plt.gca().add_patch(arrow)" }, { "code": null, "e": 10772, "s": 10406, "text": "The longest extracted chain is therefore 1 ⇌ 2 ⇌ 3 ⇌ 4 ⇌ 5. Note that we see a gradual monotonic increase in the data but, in reality, the increase or decrease in drift can happen in arbitrarily complex ways that can be detected by the time series chains approach. The key component of drifting is that the time series must contain chains with clear directionality." }, { "code": null, "e": 10804, "s": 10772, "text": "STUMPY is capable of computing:" }, { "code": null, "e": 11234, "s": 10804, "text": "anchored time series chains (ATSC) — grow a chain from a user-specified anchor (i.e., specific subsequence)all-chain set (ALLC) — a set of anchored time series chains (i.e., each chain starts with a particular subsequence) that are not subsumed by another longer chainunanchored time series chain(s) — the unconditionally longest chain within a time series (there could be more than one if there were chains with the same length)" }, { "code": null, "e": 11342, "s": 11234, "text": "anchored time series chains (ATSC) — grow a chain from a user-specified anchor (i.e., specific subsequence)" }, { "code": null, "e": 11504, "s": 11342, "text": "all-chain set (ALLC) — a set of anchored time series chains (i.e., each chain starts with a particular subsequence) that are not subsumed by another longer chain" }, { "code": null, "e": 11666, "s": 11504, "text": "unanchored time series chain(s) — the unconditionally longest chain within a time series (there could be more than one if there were chains with the same length)" }, { "code": null, "e": 11785, "s": 11666, "text": "So, what does this mean in the context of a real time series? Let’s take a look at a real example from web query data!" }, { "code": null, "e": 12165, "s": 11785, "text": "We will be looking at a noisy dataset that is under-sampled and has a growing trend, which will perfectly illustrate the idea regarding time series chains. The data contains a decade-long GoogleTrend query volume (collected weekly from 2004–2014) for the keyword Kohl’s, an American retail chain. First, we’ll download the data, extract it, and insert it into a Pandas dataframe." }, { "code": null, "e": 12345, "s": 12165, "text": "df = pd.read_csv(\"https://zenodo.org/record/4276348/files/Time_Series_Chains_Kohls_data.csv?download=1\")df.head() volume0 0.0104171 0.0104172 0.0104173 0.0000004 0.000000" }, { "code": null, "e": 12660, "s": 12345, "text": "plt.plot(df['volume'], color='black')plt.xlim(0, df.shape[0]+12)color = itertools.cycle(['white', 'gainsboro'])for i, x in enumerate(range(0, df.shape[0], 52)): plt.text(x+12, 0.9, str(2004+i), color=\"black\", fontsize=20) rect = Rectangle((x, -1), 52, 2.5, facecolor=next(color)) plt.gca().add_patch(rect)" }, { "code": null, "e": 13130, "s": 12660, "text": "The raw time series above displays ten years of web query volume for the keyword “Kohl’s”, where each alternating white and grey vertical band represents a 52 week period starting from 2004 to 2014. As depicted, the time series features a significant but unsurprising “end-of-year holiday bump”. Relating back to time series chains, we can see that the bump is generally increasing over time and so we might be able to capture this when we compute the unanchored chain." }, { "code": null, "e": 13621, "s": 13130, "text": "However, as we learned above, in order to compute any time series chains, we also need the left and right matrix profile indices. Luckily for us, according to the STUMPY documentation, the stumpy.stump() function not only returns the (bidirectional) matrix profile and the matrix profile indices in the first and second columns of the NumPy array, respectively, but the third and fourth columns consists of the left matrix profile indices and the right matrix profile indices, respectively." }, { "code": null, "e": 13763, "s": 13621, "text": "So, let’s go ahead and compute the matrix profile indices and we’ll set the window size, m = 20, which is the approximate length of a “bump”." }, { "code": null, "e": 13806, "s": 13763, "text": "m = 20mp = stumpy.stump(df['volume'], m=m)" }, { "code": null, "e": 14147, "s": 13806, "text": "Now, with our left and right matrix profile indices in hand, we are ready to call the all-chain set STUMPY function, stumpy.allc(), which not only returns the all-chain set but, as a byproduct, it also returns the unconditionally longest chain, also know as the unanchored chain. The latter of which is really what we’re most interested in." }, { "code": null, "e": 14213, "s": 14147, "text": "all_chain_set, unanchored_chain = stumpy.allc(mp[:, 2], mp[:, 3])" }, { "code": null, "e": 14677, "s": 14213, "text": "plt.plot(df['volume'], linewidth=1, color='black')for i in range(unanchored_chain.shape[0]): y = df['volume'].iloc[unanchored_chain[i]:unanchored_chain[i]+m] x = y.index.values plt.plot(x, y, linewidth=3)color = itertools.cycle(['white', 'gainsboro'])for i, x in enumerate(range(0, df.shape[0], 52)): plt.text(x+12, 0.9, str(2004+i), color=\"black\", fontsize=20) rect = Rectangle((x, -1), 52, 2.5, facecolor=next(color)) plt.gca().add_patch(rect)" }, { "code": null, "e": 15044, "s": 14677, "text": "plt.axis('off')for i in range(unanchored_chain.shape[0]): data = df['volume'].iloc[unanchored_chain[i]:unanchored_chain[i]+m].reset_index().values x = data[:, 0] y = data[:, 1] plt.axvline(x=x[0]-x.min()+(m+5)*i + 11, alpha=0.3) plt.axvline(x=x[0]-x.min()+(m+5)*i + 15, alpha=0.3, linestyle='-.') plt.plot(x-x.min()+(m+5)*i, y-y.min(), linewidth=3)" }, { "code": null, "e": 15741, "s": 15044, "text": "The discovered chain shows that over the decade, the bump transitions from a smooth bump covering the period between Thanksgiving (solid vertical line) and Christmas (dashed vertical line), to a more sharply focused bump centered on Thanksgiving. This seems to reflect the growing importance of “Cyber Monday”, a marketing term for the Monday after Thanksgiving. The phrase was created by marketing companies to persuade consumers to shop online. The term made its debut on November 28th, 2005 in a press release entitled “Cyber Monday Quickly Becoming One of the Biggest Online Shopping Days of the Year”. Note that this date coincides with the first glimpse of the sharpening peak in our chain." }, { "code": null, "e": 16260, "s": 15741, "text": "It also appears that we may have “missed” a few links in the chain. However, note that the data is noisy and under-sampled, and the “missed” bumps are too distorted to conform with the general evolving trend. This noisy example actually illustrates the robustness of the time series chains technique. As noted before, we don’t actually need “perfect” data in order to find meaningful chains. Even if some links are badly distorted, the discovered chain will still be able to include all of the other evolving patterns." }, { "code": null, "e": 16540, "s": 16260, "text": "One final consideration is the potential use of chains to predict or forecast the future. One could leverage the evolving links within the chains in order to forecast the shape of the next bump. We refer the reader to the Matrix Profile VII for further discussions on this topic." }, { "code": null, "e": 16736, "s": 16540, "text": "And that’s it! You’ve just learned the basics of how to identify directional trends, also known as chains, within your data using the matrix profile indices and leveraging stumpy.allc() function." }, { "code": null, "e": 16755, "s": 16736, "text": "Matrix Profile VII" }, { "code": null, "e": 16798, "s": 16755, "text": "Matrix Profile VII Supplementary Materials" }, { "code": null, "e": 16834, "s": 16798, "text": "STUMPY Matrix Profile Documentation" } ]
How to detect the Internet connection is offline or not using JavaScript? - GeeksforGeeks
28 Jan, 2020 In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires bandwidth and can also affect usability. Yet JavaScript’s Browser Object Model(BOM) provides a direct way to detect browser’s connectivity status i.e. whether the browser is online or offline. To perform this check, targeting all possible browsers out there, we will be using the following property : navigator.onLine Syntax: function isOnline() { return ( navigator.onLine) } Example: This example displays a button if it is clicked, It will show the connectivity status. <!DOCTYPE html><html> <body> <p>Click the button to check if the browser is online.</p> <button onclick="isOnline()"> Click Me </button> <p id="demo"></p> <script> function isOnline() { if (navigator.onLine) { document.getElementById( "demo").innerHTML = "Online"; } else { document.getElementById( "demo").innerHTML = "Offline"; } } </script> </body> </html> Note: The minimum version of browsers that supports the property: Google Chrome: 14.0 Internet Explorer: Yes Firefox: 3.5 Safari: 5.0.4 Opera: Yes Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. JavaScript-Misc Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form HTML Cheat Sheet - A Basic Guide to HTML 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": 25967, "s": 25939, "text": "\n28 Jan, 2020" }, { "code": null, "e": 26355, "s": 25967, "text": "In some cases, it is necessary to determine whether the browser is online or offline before performing a required task. Many developers use AJAX to determine the connection status of the browser (online or offline) by sending a request to the server. However, this is not a good method for determining the state of the browser because it requires bandwidth and can also affect usability." }, { "code": null, "e": 26507, "s": 26355, "text": "Yet JavaScript’s Browser Object Model(BOM) provides a direct way to detect browser’s connectivity status i.e. whether the browser is online or offline." }, { "code": null, "e": 26615, "s": 26507, "text": "To perform this check, targeting all possible browsers out there, we will be using the following property :" }, { "code": null, "e": 26632, "s": 26615, "text": "navigator.onLine" }, { "code": null, "e": 26640, "s": 26632, "text": "Syntax:" }, { "code": null, "e": 26697, "s": 26640, "text": "function isOnline() { \n return ( navigator.onLine) \n}" }, { "code": null, "e": 26793, "s": 26697, "text": "Example: This example displays a button if it is clicked, It will show the connectivity status." }, { "code": "<!DOCTYPE html><html> <body> <p>Click the button to check if the browser is online.</p> <button onclick=\"isOnline()\"> Click Me </button> <p id=\"demo\"></p> <script> function isOnline() { if (navigator.onLine) { document.getElementById( \"demo\").innerHTML = \"Online\"; } else { document.getElementById( \"demo\").innerHTML = \"Offline\"; } } </script> </body> </html>", "e": 27304, "s": 26793, "text": null }, { "code": null, "e": 27370, "s": 27304, "text": "Note: The minimum version of browsers that supports the property:" }, { "code": null, "e": 27390, "s": 27370, "text": "Google Chrome: 14.0" }, { "code": null, "e": 27413, "s": 27390, "text": "Internet Explorer: Yes" }, { "code": null, "e": 27426, "s": 27413, "text": "Firefox: 3.5" }, { "code": null, "e": 27440, "s": 27426, "text": "Safari: 5.0.4" }, { "code": null, "e": 27451, "s": 27440, "text": "Opera: Yes" }, { "code": null, "e": 27459, "s": 27451, "text": "Output:" }, { "code": null, "e": 27596, "s": 27459, "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": 27612, "s": 27596, "text": "JavaScript-Misc" }, { "code": null, "e": 27619, "s": 27612, "text": "Picked" }, { "code": null, "e": 27624, "s": 27619, "text": "HTML" }, { "code": null, "e": 27641, "s": 27624, "text": "Web Technologies" }, { "code": null, "e": 27668, "s": 27641, "text": "Web technologies Questions" }, { "code": null, "e": 27673, "s": 27668, "text": "HTML" }, { "code": null, "e": 27771, "s": 27673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27819, "s": 27771, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27843, "s": 27819, "text": "REST API (Introduction)" }, { "code": null, "e": 27893, "s": 27843, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27943, "s": 27893, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27984, "s": 27943, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28024, "s": 27984, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28057, "s": 28024, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28102, "s": 28057, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28145, "s": 28102, "text": "How to fetch data from an API in ReactJS ?" } ]
CSS Buttons - Pushy Buttons Usage
Pushy Buttons library is a small CSS Pressable Buttons library. To load the pushy-buttons.min.css library, download the css from github and paste the following line in the <head> section of the webpage. <head> <link rel = "stylesheet" href = "pushy-buttons.min.css"> </head> Create a button using html button tag and add styles btn, btn-blue with size specifier btn-lg. <html> <head> <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css"> </head> <body> <button class = "btn btn--blue">Submit</button> </body> </html> It will produce the following output − You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes. <html> <head> <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css"> </head> <body> <button class = "btn btn--lg btn--blue">Large</button> <button class = "btn btn--df btn--blue">Normal</button> <button class = "btn btn--md btn--blue">Medium</button> <button class = "btn btn--sm btn--blue">Small</button> </body> </html> It will produce the following output − Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button. <html> <head> <link rel = "stylesheet" href = "/css_buttons/pushy-buttons.min.css"> </head> <body> <button class = "btn btn--lg btn--red">Large</button> <button class = "btn btn--df btn--green">Normal</button> <button class = "btn btn--md btn--blue">Medium</button> </body> </html> It will produce the following output − 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 1962, "s": 1898, "text": "Pushy Buttons library is a small CSS Pressable Buttons library." }, { "code": null, "e": 2101, "s": 1962, "text": "To load the pushy-buttons.min.css library, download the css from github and paste the following line in the <head> section of the webpage." }, { "code": null, "e": 2177, "s": 2101, "text": "<head>\n <link rel = \"stylesheet\" href = \"pushy-buttons.min.css\">\n</head>\n" }, { "code": null, "e": 2272, "s": 2177, "text": "Create a button using html button tag and add styles btn, btn-blue with size specifier btn-lg." }, { "code": null, "e": 2463, "s": 2272, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"/css_buttons/pushy-buttons.min.css\">\n </head>\n \n <body>\n <button class = \"btn btn--blue\">Submit</button>\n </body>\n</html>" }, { "code": null, "e": 2502, "s": 2463, "text": "It will produce the following output −" }, { "code": null, "e": 2690, "s": 2502, "text": "You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes." }, { "code": null, "e": 3073, "s": 2690, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"/css_buttons/pushy-buttons.min.css\">\n </head>\n \n <body>\n <button class = \"btn btn--lg btn--blue\">Large</button>\n <button class = \"btn btn--df btn--blue\">Normal</button>\n <button class = \"btn btn--md btn--blue\">Medium</button>\n <button class = \"btn btn--sm btn--blue\">Small</button>\n </body>\n</html>" }, { "code": null, "e": 3112, "s": 3073, "text": "It will produce the following output −" }, { "code": null, "e": 3245, "s": 3112, "text": "Just like size, you can define the color of the button using CSS. The following example shows how to change the color of the button." }, { "code": null, "e": 3567, "s": 3245, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"/css_buttons/pushy-buttons.min.css\">\n </head>\n \n <body>\n <button class = \"btn btn--lg btn--red\">Large</button>\n <button class = \"btn btn--df btn--green\">Normal</button>\n <button class = \"btn btn--md btn--blue\">Medium</button>\n </body>\n</html>" }, { "code": null, "e": 3606, "s": 3567, "text": "It will produce the following output −" }, { "code": null, "e": 3641, "s": 3606, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3655, "s": 3641, "text": " Anadi Sharma" }, { "code": null, "e": 3690, "s": 3655, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3707, "s": 3690, "text": " Frahaan Hussain" }, { "code": null, "e": 3742, "s": 3707, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3773, "s": 3742, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3808, "s": 3773, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3839, "s": 3808, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3874, "s": 3839, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3905, "s": 3874, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3938, "s": 3905, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 3969, "s": 3938, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3976, "s": 3969, "text": " Print" }, { "code": null, "e": 3987, "s": 3976, "text": " Add Notes" } ]
Check if a large number is divisible by 3 or not in C++
Here we will see how to check a number is divisible by 3 or not. In this case the number is very large number. So we put the number as string. A number will be divisible by 3, if the sum of digits is divisible by 3. Live Demo #include <bits/stdc++.h> using namespace std; bool isDiv3(string num){ int n = num.length(); long sum = accumulate(begin(num), end(num), 0) - '0' * n; if(sum % 3 == 0) return true; return false; } int main() { string num = "3635883959606670431112222"; if(isDiv3(num)){ cout << "Divisible"; } else { cout << "Not Divisible"; } } Divisible
[ { "code": null, "e": 1205, "s": 1062, "text": "Here we will see how to check a number is divisible by 3 or not. In this case the number is very large number. So we put the number as string." }, { "code": null, "e": 1278, "s": 1205, "text": "A number will be divisible by 3, if the sum of digits is divisible by 3." }, { "code": null, "e": 1289, "s": 1278, "text": " Live Demo" }, { "code": null, "e": 1662, "s": 1289, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool isDiv3(string num){\n int n = num.length();\n long sum = accumulate(begin(num), end(num), 0) - '0' * n;\n if(sum % 3 == 0)\n return true;\n return false;\n}\nint main() {\n string num = \"3635883959606670431112222\";\n if(isDiv3(num)){\n cout << \"Divisible\";\n } else {\n cout << \"Not Divisible\";\n }\n}" }, { "code": null, "e": 1672, "s": 1662, "text": "Divisible" } ]
C++ Program to Implement Stack in STL
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be FILO (First In first out) or LIFO (Last In First Out) Begin Declare stack vector. Take the input as per choice. Call the functions within switch operation: s.size() = Returns the size of stack. s.push() = It is used to insert elements to the stack. s.pop() = To pop out the value from the stack. s.top() = Returns a reference to the top most element of stack. End. #include <iostream> #include <stack> #include <string> #include <cstdlib> using namespace std; int main() { stack<int> s; int c, i; while (1) { cout<<"1.Size of the Stack"<<endl; cout<<"2.Insert Element into the Stack"<<endl; cout<<"3.Delete Element from the Stack"<<endl; cout<<"4.Top Element of the Stack"<<endl; cout<<"5.Exit"<<endl; cout<<"Enter your Choice: "; cin>>c; switch(c) { case 1: cout<<"Size of the stack: "; cout<<s.size()<<endl; break; case 2: cout<<"Enter value to be inserted: "; cin>>i; s.push(i); break; case 3: i = s.top(); if (!s.empty()) { s.pop(); cout<<i<<" Deleted"<<endl; }else { cout<<"Stack is Empty"<<endl; } break; case 4: cout<<"Top Element of the Stack: "; cout<<s.top()<<endl; break; case 5: exit(1); break; default: cout<<"Wrong Choice"<<endl; } } return 0; } 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 1 Size of the stack: 0 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 2 Enter value to be inserted: 1 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 2 Enter value to be inserted: 7 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 2 Enter value to be inserted: 6 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 2 Enter value to be inserted: 10 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 2 Enter value to be inserted: 4 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 1 Size of the stack: 5 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 3 4 Deleted 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 4 Top Element of the Stack: 10 1.Size of the Stack 2.Insert Element into the Stack 3.Delete Element from the Stack 4.Top Element of the Stack 5.Exit Enter your Choice: 5 Exit code: 1
[ { "code": null, "e": 1238, "s": 1062, "text": "Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be FILO (First In first out) or LIFO (Last In First Out)" }, { "code": null, "e": 1570, "s": 1238, "text": "Begin\n Declare stack vector.\n Take the input as per choice.\n Call the functions within switch operation:\n s.size() = Returns the size of stack.\n s.push() = It is used to insert elements to the stack.\n s.pop() = To pop out the value from the stack.\n s.top() = Returns a reference to the top most element of stack.\nEnd." }, { "code": null, "e": 2737, "s": 1570, "text": "#include <iostream>\n#include <stack>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n stack<int> s;\n int c, i;\n while (1) {\n cout<<\"1.Size of the Stack\"<<endl;\n cout<<\"2.Insert Element into the Stack\"<<endl;\n cout<<\"3.Delete Element from the Stack\"<<endl;\n cout<<\"4.Top Element of the Stack\"<<endl;\n cout<<\"5.Exit\"<<endl;\n cout<<\"Enter your Choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Size of the stack: \";\n cout<<s.size()<<endl;\n break;\n case 2:\n cout<<\"Enter value to be inserted: \";\n cin>>i;\n s.push(i);\n break;\n case 3:\n i = s.top();\n if (!s.empty()) {\n s.pop();\n cout<<i<<\" Deleted\"<<endl;\n }else {\n cout<<\"Stack is Empty\"<<endl;\n }\n break;\n case 4:\n cout<<\"Top Element of the Stack: \";\n cout<<s.top()<<endl;\n break;\n case 5:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\n return 0;\n}" }, { "code": null, "e": 4382, "s": 2737, "text": "1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 1\nSize of the stack: 0\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 1\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 7\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 6\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 10\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 4\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 1\nSize of the stack: 5\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 3\n4 Deleted\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\n\nEnter your Choice: 4\nTop Element of the Stack: 10\n1.Size of the Stack\n2.Insert Element into the Stack\n3.Delete Element from the Stack\n4.Top Element of the Stack\n5.Exit\nEnter your Choice: 5\n\nExit code: 1" } ]
Encapsulation in C++ - GeeksforGeeks
24 Nov, 2021 In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them.Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section. In C++ encapsulation can be implemented using Class and access modifiers. Look at the below program: // c++ program to explain// Encapsulation #include<iostream>using namespace std; class Encapsulation{ private: // data hidden from outside world int x; public: // function to set value of // variable x void set(int a) { x =a; } // function to return value of // variable x int get() { return x; }}; // main functionint main(){ Encapsulation obj; obj.set(5); cout<<obj.get(); return 0;} output: 5 In the above program the variable x is made private. This variable can be accessed and manipulated only using the functions get() and set() which are present inside the class. Thus we can say that here, the variable x and the functions get() and set() are binded together which is nothing but encapsulation. Role of access specifiers in encapsulation As we have seen in above example, access specifiers plays an important role in implementing encapsulation in C++. The process of implementing encapsulation can be sub-divided into two steps: The data members should be labeled as private using the private access specifiersThe member function which manipulates the data members should be labeled as public using the public access specifier The data members should be labeled as private using the private access specifiers The member function which manipulates the data members should be labeled as public using the public access specifier This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-class C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Socket Programming in C/C++ Virtual Function in C++ Templates in C++ with Examples rand() and srand() in C/C++ getline (string) in C++ Left Shift and Right Shift Operators in C/C++
[ { "code": null, "e": 26960, "s": 26932, "text": "\n24 Nov, 2021" }, { "code": null, "e": 28047, "s": 26960, "text": "In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them.Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”." }, { "code": null, "e": 28264, "s": 28047, "text": "Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section." }, { "code": null, "e": 28365, "s": 28264, "text": "In C++ encapsulation can be implemented using Class and access modifiers. Look at the below program:" }, { "code": "// c++ program to explain// Encapsulation #include<iostream>using namespace std; class Encapsulation{ private: // data hidden from outside world int x; public: // function to set value of // variable x void set(int a) { x =a; } // function to return value of // variable x int get() { return x; }}; // main functionint main(){ Encapsulation obj; obj.set(5); cout<<obj.get(); return 0;}", "e": 28911, "s": 28365, "text": null }, { "code": null, "e": 28919, "s": 28911, "text": "output:" }, { "code": null, "e": 28922, "s": 28919, "text": "5\n" }, { "code": null, "e": 29230, "s": 28922, "text": "In the above program the variable x is made private. This variable can be accessed and manipulated only using the functions get() and set() which are present inside the class. Thus we can say that here, the variable x and the functions get() and set() are binded together which is nothing but encapsulation." }, { "code": null, "e": 29273, "s": 29230, "text": "Role of access specifiers in encapsulation" }, { "code": null, "e": 29464, "s": 29273, "text": "As we have seen in above example, access specifiers plays an important role in implementing encapsulation in C++. The process of implementing encapsulation can be sub-divided into two steps:" }, { "code": null, "e": 29662, "s": 29464, "text": "The data members should be labeled as private using the private access specifiersThe member function which manipulates the data members should be labeled as public using the public access specifier" }, { "code": null, "e": 29744, "s": 29662, "text": "The data members should be labeled as private using the private access specifiers" }, { "code": null, "e": 29861, "s": 29744, "text": "The member function which manipulates the data members should be labeled as public using the public access specifier" }, { "code": null, "e": 30158, "s": 29861, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30283, "s": 30158, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30293, "s": 30283, "text": "cpp-class" }, { "code": null, "e": 30297, "s": 30293, "text": "C++" }, { "code": null, "e": 30301, "s": 30297, "text": "CPP" }, { "code": null, "e": 30399, "s": 30301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30417, "s": 30399, "text": "Vector in C++ STL" }, { "code": null, "e": 30463, "s": 30417, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30486, "s": 30463, "text": "std::sort() in C++ STL" }, { "code": null, "e": 30513, "s": 30486, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30541, "s": 30513, "text": "Socket Programming in C/C++" }, { "code": null, "e": 30565, "s": 30541, "text": "Virtual Function in C++" }, { "code": null, "e": 30596, "s": 30565, "text": "Templates in C++ with Examples" }, { "code": null, "e": 30624, "s": 30596, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 30648, "s": 30624, "text": "getline (string) in C++" } ]
Program to find GCD or HCF of two numbers - GeeksforGeeks
03 Feb, 2022 GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14. For solution suppose a=98 & b=56 a>b so put a= a-b and b is remain same so a=98-56=42 & b= 56 . Now b>a so b=b-a and a is same b= 56-42 = 14 & a= 42 . 42 is 3 times of 14 so HCF is 14 . likewise a=36 & b=60 ,here b>a so b = 24 & a= 36 now a>b so a= 12 & b= 24 . 12 is HCF of 36 and 60 . This concept is always satisfying. A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in both numbers. Finally return product of elements in the intersection.An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number. C++ C Java Python3 C# PHP Javascript // C++ program to find GCD of two numbers#include <iostream>using namespace std;// Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b); return 0;} // C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf("GCD of %d and %d is %d ", a, b, gcd(a, b)); return 0;} // Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} # Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza // C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} // This code is contributed by anuj_67. <?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if($a == $b) return $a ; // a is greater if($a > $b) return gcd( $a-$b , $b ) ; return gcd( $a , $b-$a ) ;} // Driver code$a = 98 ;$b = 56 ; echo "GCD of $a and $b is ", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?> <script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above function let a = 98, b = 56; document.write("GCD of "+ a + " and " + b + " is " + gcd(a, b)); // This code is contributed by Mayank Tyagi </script> Output: GCD of 98 and 56 is 14 Time Complexity: O(max(a,b)) Auxiliary Space: O(max(a,b)) Dynamic Programming Approach (Top Down Using Memoization) : C++ Java Python3 C# Javascript // C++ program to find GCD of two numbers#include <bits/stdc++.h>using namespace std; int static dp[1001][1001]; // Function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b];} // Driver program to test above functionint main(){ int a = 98, b = 56; memset(dp, -1, sizeof(dp)); cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b); return 0;} // Java program to find GCD of two numbersimport java.util.*;public class GFG{ static int [][]dp = new int[1001][1001]; // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b]; } // Driver method public static void main(String[] args) { for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i][j] = -1; } } int a = 98, b = 56; System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} // This code is contributed by Samim Hossain Mondal. # function to return gcd of a and b # Taking the matrix as globallydp = [[-1 for i in range(1001)] for j in range(1001)] def gcd(a,b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a if(dp[a][b] != -1): return dp[a][b] # a is greater if (a > b): dp[a][b] = gcd(a-b, b) else: dp[a][b] = gcd(a, b-a) return dp[a][b] # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Samim Hossain Mondal. // C# program to find GCD of two numbersusing System;class GFG{ static int [,]dp = new int[1001, 1001]; // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a, b] != -1) return dp[a, b]; // a is greater if (a > b) dp[a, b] = gcd(a-b, b); // b is greater else dp[a, b] = gcd(a, b-a); // return dp return dp[a, b]; } // Driver method public static void Main() { for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i, j] = -1; } } int a = 98, b = 56; Console.Write("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} // This code is contributed by Samim Hossain Mondal. //<script>// Javascript program to find GCD of two numbersvar dp = new Array(1001); // Loop to create 2D array using 1D arrayfor (var i = 0; i < dp.length; i++) { dp[i] = new Array(1001);} // Function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b];} // Driver program to test above function let a = 98, b = 56; for(let i = 0; i < 1001; i++) { for(let j = 0; j < 1001; j++) { dp[i][j] = -1; } } document.write("GCD of "+ a + " and " + b + " is " + gcd(a, b)); // This code is contributed by Samim Hossain Mondal </script> GCD of 98 and 56 is 14 Time Complexity: O(max(a,b)) Auxiliary Space: O(1) A more efficient solution is to use modulo operator in Euclidean algorithm. C++ C Java Python3 C# PHP Javascript // C++ program to find GCD of two numbers#include <iostream>using namespace std;// Recursive function to return gcd of a and b in single lineint gcd(int a, int b){ return b == 0 ? a : gcd(b, a % b); } // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b); return 0;} // C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf("GCD of %d and %d is %d ", a, b, gcd(a, b)); return 0;} // Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} # Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza // C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine("GCD of " + a +" and " + b + " is " + gcd(a, b)); }} // This code is contributed by anuj_67. <?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($b==0) return $a ; return gcd( $b , $a % $b ) ;} // Driver code$a = 98 ;$b = 56 ; echo "GCD of $a and $b is ", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?> <script> // Javascript program to find GCD of two number // Recursive function to return gcd of a and b function gcd(a, b){ // Everything divides 0 if(b == 0){ return a; } return gcd(b, a % b);} // Driver codelet a = 98;let b = 56; document.write(`GCD of ${a} and ${b} is ${gcd(a, b)}`); // This code is contributed by _saurabh_jaiswal </script> Output: GCD of 98 and 56 is 14 Time Complexity: O(log(max(a,b)) Auxiliary Space: O(log(max(a,b)) The time complexity for the above algorithm is O(log(max(a,b))) the derivation for this is obtained from the analysis of the worst-case scenario. What we do is we ask what are the 2 least numbers that take 1 step, those would be (1,1). If we want to increase the number of steps to 2 while keeping the numbers as low as possible as we can take the numbers to be (1,2). Similarly, for 3 steps, the numbers would be (2,3), 4 would be (3,5), 5 would be (5,8). So we can notice a pattern here, for the nth step the numbers would be (fib(n),fib(n+1)). So the worst-case time complexity would be O(n) where a>= fib(n) and b>= fib(n+1). Now Fibonacci series is an exponentially growing series where the ratio of nth/(n-1)th term approaches (sqrt(5)-1)/2 which is also called the golden ratio. So we can see that the time complexity of the algorithm increases linearly as the terms grow exponentially hence the time complexity would be log(max(a,b)). Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above vt_m SoumikMondal SidhantAgarwal1 ankit jhunjhunwala mayanktyagi1709 _saurabh_jaiswal sukhsoni803 samim2000 binarybeast amartyaghoshgfg prophet1999 GCD-LCM SAP Labs Mathematical School Programming SAP Labs Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24550, "s": 24522, "text": "\n03 Feb, 2022" }, { "code": null, "e": 24676, "s": 24550, "text": "GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. " }, { "code": null, "e": 24774, "s": 24676, "text": "For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14. For solution suppose a=98 & b=56 " }, { "code": null, "e": 24876, "s": 24774, "text": "a>b so put a= a-b and b is remain same so a=98-56=42 & b= 56 . Now b>a so b=b-a and a is same " }, { "code": null, "e": 25110, "s": 24876, "text": "b= 56-42 = 14 & a= 42 . 42 is 3 times of 14 so HCF is 14 . likewise a=36 & b=60 ,here b>a so b = 24 & a= 36 now a>b so a= 12 & b= 24 . 12 is HCF of 36 and 60 . This concept is always satisfying. " }, { "code": null, "e": 25498, "s": 25110, "text": " A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in both numbers. Finally return product of elements in the intersection.An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number. " }, { "code": null, "e": 25502, "s": 25498, "text": "C++" }, { "code": null, "e": 25504, "s": 25502, "text": "C" }, { "code": null, "e": 25509, "s": 25504, "text": "Java" }, { "code": null, "e": 25517, "s": 25509, "text": "Python3" }, { "code": null, "e": 25520, "s": 25517, "text": "C#" }, { "code": null, "e": 25524, "s": 25520, "text": "PHP" }, { "code": null, "e": 25535, "s": 25524, "text": "Javascript" }, { "code": "// C++ program to find GCD of two numbers#include <iostream>using namespace std;// Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<\"GCD of \"<<a<<\" and \"<<b<<\" is \"<<gcd(a, b); return 0;}", "e": 26053, "s": 25535, "text": null }, { "code": "// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf(\"GCD of %d and %d is %d \", a, b, gcd(a, b)); return 0;}", "e": 26547, "s": 26053, "text": null }, { "code": "// Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }}", "e": 27152, "s": 26547, "text": null }, { "code": "# Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a # a is greater if (a > b): return gcd(a-b, b) return gcd(a, b-a) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza", "e": 27620, "s": 27152, "text": null }, { "code": "// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a - b, b); return gcd(a, b - a); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by anuj_67.", "e": 28330, "s": 27620, "text": null }, { "code": "<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if ($a == 0) return $b; if ($b == 0) return $a; // base case if($a == $b) return $a ; // a is greater if($a > $b) return gcd( $a-$b , $b ) ; return gcd( $a , $b-$a ) ;} // Driver code$a = 98 ;$b = 56 ; echo \"GCD of $a and $b is \", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>", "e": 28825, "s": 28330, "text": null }, { "code": "<script> // Javascript program to find GCD of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a-b, b); return gcd(a, b-a);} // Driver program to test above function let a = 98, b = 56; document.write(\"GCD of \"+ a + \" and \" + b + \" is \" + gcd(a, b)); // This code is contributed by Mayank Tyagi </script>", "e": 29357, "s": 28825, "text": null }, { "code": null, "e": 29366, "s": 29357, "text": "Output: " }, { "code": null, "e": 29389, "s": 29366, "text": "GCD of 98 and 56 is 14" }, { "code": null, "e": 29418, "s": 29389, "text": "Time Complexity: O(max(a,b))" }, { "code": null, "e": 29447, "s": 29418, "text": "Auxiliary Space: O(max(a,b))" }, { "code": null, "e": 29507, "s": 29447, "text": "Dynamic Programming Approach (Top Down Using Memoization) :" }, { "code": null, "e": 29511, "s": 29507, "text": "C++" }, { "code": null, "e": 29516, "s": 29511, "text": "Java" }, { "code": null, "e": 29524, "s": 29516, "text": "Python3" }, { "code": null, "e": 29527, "s": 29524, "text": "C#" }, { "code": null, "e": 29538, "s": 29527, "text": "Javascript" }, { "code": "// C++ program to find GCD of two numbers#include <bits/stdc++.h>using namespace std; int static dp[1001][1001]; // Function to return gcd of a and bint gcd(int a, int b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b];} // Driver program to test above functionint main(){ int a = 98, b = 56; memset(dp, -1, sizeof(dp)); cout<<\"GCD of \"<<a<<\" and \"<<b<<\" is \"<<gcd(a, b); return 0;}", "e": 30293, "s": 29538, "text": null }, { "code": "// Java program to find GCD of two numbersimport java.util.*;public class GFG{ static int [][]dp = new int[1001][1001]; // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b]; } // Driver method public static void main(String[] args) { for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i][j] = -1; } } int a = 98, b = 56; System.out.println(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by Samim Hossain Mondal.", "e": 31332, "s": 30293, "text": null }, { "code": "# function to return gcd of a and b # Taking the matrix as globallydp = [[-1 for i in range(1001)] for j in range(1001)] def gcd(a,b): # Everything divides 0 if (a == 0): return b if (b == 0): return a # base case if (a == b): return a if(dp[a][b] != -1): return dp[a][b] # a is greater if (a > b): dp[a][b] = gcd(a-b, b) else: dp[a][b] = gcd(a, b-a) return dp[a][b] # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Samim Hossain Mondal.", "e": 31994, "s": 31332, "text": null }, { "code": "// C# program to find GCD of two numbersusing System;class GFG{ static int [,]dp = new int[1001, 1001]; // Recursive function to return gcd of a and b static int gcd(int a, int b) { // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a, b] != -1) return dp[a, b]; // a is greater if (a > b) dp[a, b] = gcd(a-b, b); // b is greater else dp[a, b] = gcd(a, b-a); // return dp return dp[a, b]; } // Driver method public static void Main() { for(int i = 0; i < 1001; i++) { for(int j = 0; j < 1001; j++) { dp[i, j] = -1; } } int a = 98, b = 56; Console.Write(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by Samim Hossain Mondal.", "e": 32995, "s": 31994, "text": null }, { "code": "//<script>// Javascript program to find GCD of two numbersvar dp = new Array(1001); // Loop to create 2D array using 1D arrayfor (var i = 0; i < dp.length; i++) { dp[i] = new Array(1001);} // Function to return gcd of a and bfunction gcd(a, b){ // Everything divides 0 if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // if a value is already // present in dp if(dp[a][b] != -1) return dp[a][b]; // a is greater if (a > b) dp[a][b] = gcd(a-b, b); // b is greater else dp[a][b] = gcd(a, b-a); // return dp return dp[a][b];} // Driver program to test above function let a = 98, b = 56; for(let i = 0; i < 1001; i++) { for(let j = 0; j < 1001; j++) { dp[i][j] = -1; } } document.write(\"GCD of \"+ a + \" and \" + b + \" is \" + gcd(a, b)); // This code is contributed by Samim Hossain Mondal </script>", "e": 33970, "s": 32995, "text": null }, { "code": null, "e": 33993, "s": 33970, "text": "GCD of 98 and 56 is 14" }, { "code": null, "e": 34022, "s": 33993, "text": "Time Complexity: O(max(a,b))" }, { "code": null, "e": 34044, "s": 34022, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 34120, "s": 34044, "text": "A more efficient solution is to use modulo operator in Euclidean algorithm." }, { "code": null, "e": 34124, "s": 34120, "text": "C++" }, { "code": null, "e": 34126, "s": 34124, "text": "C" }, { "code": null, "e": 34131, "s": 34126, "text": "Java" }, { "code": null, "e": 34139, "s": 34131, "text": "Python3" }, { "code": null, "e": 34142, "s": 34139, "text": "C#" }, { "code": null, "e": 34146, "s": 34142, "text": "PHP" }, { "code": null, "e": 34157, "s": 34146, "text": "Javascript" }, { "code": "// C++ program to find GCD of two numbers#include <iostream>using namespace std;// Recursive function to return gcd of a and b in single lineint gcd(int a, int b){ return b == 0 ? a : gcd(b, a % b); } // Driver program to test above functionint main(){ int a = 98, b = 56; cout<<\"GCD of \"<<a<<\" and \"<<b<<\" is \"<<gcd(a, b); return 0;}", "e": 34507, "s": 34157, "text": null }, { "code": "// C program to find GCD of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Driver program to test above functionint main(){ int a = 98, b = 56; printf(\"GCD of %d and %d is %d \", a, b, gcd(a, b)); return 0;}", "e": 34836, "s": 34507, "text": null }, { "code": "// Java program to find GCD of two numbersclass Test{ // Recursive function to return gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void main(String[] args) { int a = 98, b = 56; System.out.println(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }}", "e": 35224, "s": 34836, "text": null }, { "code": "# Recursive function to return gcd of a and bdef gcd(a,b): # Everything divides 0 if (b == 0): return a return gcd(b, a%b) # Driver program to test above functiona = 98b = 56if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b))else: print('not found') # This code is contributed by Danish Raza", "e": 35553, "s": 35224, "text": null }, { "code": "// C# program to find GCD of two// numbersusing System; class GFG { // Recursive function to return // gcd of a and b static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Driver method public static void Main() { int a = 98, b = 56; Console.WriteLine(\"GCD of \" + a +\" and \" + b + \" is \" + gcd(a, b)); }} // This code is contributed by anuj_67.", "e": 36031, "s": 35553, "text": null }, { "code": "<?php// PHP program to find GCD// of two numbers // Recursive function to// return gcd of a and bfunction gcd($a, $b){ // Everything divides 0 if($b==0) return $a ; return gcd( $b , $a % $b ) ;} // Driver code$a = 98 ;$b = 56 ; echo \"GCD of $a and $b is \", gcd($a , $b) ; // This code is contributed by Anivesh Tiwari?>", "e": 36368, "s": 36031, "text": null }, { "code": "<script> // Javascript program to find GCD of two number // Recursive function to return gcd of a and b function gcd(a, b){ // Everything divides 0 if(b == 0){ return a; } return gcd(b, a % b);} // Driver codelet a = 98;let b = 56; document.write(`GCD of ${a} and ${b} is ${gcd(a, b)}`); // This code is contributed by _saurabh_jaiswal </script>", "e": 36727, "s": 36368, "text": null }, { "code": null, "e": 36736, "s": 36727, "text": "Output: " }, { "code": null, "e": 36759, "s": 36736, "text": "GCD of 98 and 56 is 14" }, { "code": null, "e": 36792, "s": 36759, "text": "Time Complexity: O(log(max(a,b))" }, { "code": null, "e": 36825, "s": 36792, "text": "Auxiliary Space: O(log(max(a,b))" }, { "code": null, "e": 37457, "s": 36825, "text": "The time complexity for the above algorithm is O(log(max(a,b))) the derivation for this is obtained from the analysis of the worst-case scenario. What we do is we ask what are the 2 least numbers that take 1 step, those would be (1,1). If we want to increase the number of steps to 2 while keeping the numbers as low as possible as we can take the numbers to be (1,2). Similarly, for 3 steps, the numbers would be (2,3), 4 would be (3,5), 5 would be (5,8). So we can notice a pattern here, for the nth step the numbers would be (fib(n),fib(n+1)). So the worst-case time complexity would be O(n) where a>= fib(n) and b>= fib(n+1). " }, { "code": null, "e": 37770, "s": 37457, "text": "Now Fibonacci series is an exponentially growing series where the ratio of nth/(n-1)th term approaches (sqrt(5)-1)/2 which is also called the golden ratio. So we can see that the time complexity of the algorithm increases linearly as the terms grow exponentially hence the time complexity would be log(max(a,b))." }, { "code": null, "e": 37984, "s": 37770, "text": "Please refer GCD of more than two (or array) numbers to find HCF of more than two numbers.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 37989, "s": 37984, "text": "vt_m" }, { "code": null, "e": 38002, "s": 37989, "text": "SoumikMondal" }, { "code": null, "e": 38018, "s": 38002, "text": "SidhantAgarwal1" }, { "code": null, "e": 38037, "s": 38018, "text": "ankit jhunjhunwala" }, { "code": null, "e": 38053, "s": 38037, "text": "mayanktyagi1709" }, { "code": null, "e": 38070, "s": 38053, "text": "_saurabh_jaiswal" }, { "code": null, "e": 38082, "s": 38070, "text": "sukhsoni803" }, { "code": null, "e": 38092, "s": 38082, "text": "samim2000" }, { "code": null, "e": 38104, "s": 38092, "text": "binarybeast" }, { "code": null, "e": 38120, "s": 38104, "text": "amartyaghoshgfg" }, { "code": null, "e": 38132, "s": 38120, "text": "prophet1999" }, { "code": null, "e": 38140, "s": 38132, "text": "GCD-LCM" }, { "code": null, "e": 38149, "s": 38140, "text": "SAP Labs" }, { "code": null, "e": 38162, "s": 38149, "text": "Mathematical" }, { "code": null, "e": 38181, "s": 38162, "text": "School Programming" }, { "code": null, "e": 38190, "s": 38181, "text": "SAP Labs" }, { "code": null, "e": 38203, "s": 38190, "text": "Mathematical" }, { "code": null, "e": 38301, "s": 38203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38344, "s": 38301, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 38393, "s": 38344, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 38427, "s": 38393, "text": "Program for factorial of a number" }, { "code": null, "e": 38448, "s": 38427, "text": "Operators in C / C++" }, { "code": null, "e": 38491, "s": 38448, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 38509, "s": 38491, "text": "Python Dictionary" }, { "code": null, "e": 38525, "s": 38509, "text": "Arrays in C/C++" }, { "code": null, "e": 38544, "s": 38525, "text": "Inheritance in C++" }, { "code": null, "e": 38569, "s": 38544, "text": "Reverse a string in Java" } ]
How to Get First Column of Pandas DataFrame? - GeeksforGeeks
28 Nov, 2021 In this article, we will discuss how to get the first column of the pandas dataframe in Python programming language. This function is used to get the first column using slice operator. for the rows we extract all of them, for columns specify the index for first column. Syntax : dataframe.iloc[:, 0] where. dataframe is the input dataframe The slice operation will be like: [row_start:row_end , column_start, column_end] where, row_start refers start row with 0 position as index row_end refers last row with n th position as index column_start refers start column with 0 position as index column_end refers last column with n th position as index The following alternative can also be employed. Syntax : dataframe.iloc[:, :1] where. dataframe is the input dataframe. Both of these will return the dataframe datatype. Example: Python program to get the first column by using above approaches Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print("--------------") # get first column by returning seriesprint(data.iloc[:, 0]) print("--------------") # get first column by returning dataframeprint(data.iloc[:, :1]) Output: This method will return the column based on index. So, we have to give 0 to get the first column Syntax: dataframe[dataframe.columns[0]] where dataframe is the input dataframe columns[0] represent first column Example: Python program to get the first column using columns[] Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print("--------------") # get first column by returning dataframe# using columns[] methodprint(data[data.columns[0]]) Output: We can use the first column name to get the first column. Syntax: dataframe.first_column Example: Python code to get the first column using column name Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print("--------------") # get first column by returning dataframe# using column_nameprint(data.id) Output: We can also use the head() function within this to display the number of rows in the first column. Example: Python code to get the first column using the column name Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print("--------------") # get first column by returning dataframe# using column_name# display 1 rowprint(data.id.head(1))print("--------------") # get first column by returning dataframe# using column_name# display 2 rowsprint(data.id.head(2))print("--------------") # get first column by returning dataframe# using column_name# display 4 rowsprint(data.id.head(4)) Output: This function by default returns the top rows of the dataframe. To return the column we have to Transpose (Interchange rows to columns) the dataframe by using T function and get 1st column. Syntax: dataframe.T.head(1).T Example: Python code to get the first column using column name Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "id": [7058, 7059, 7072, 7054], "name": ['sravan', 'jyothika', 'harsha', 'ramya'], "subjects": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print("--------------")# using headprint(data.T.head(1).T) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25672, "s": 25555, "text": "In this article, we will discuss how to get the first column of the pandas dataframe in Python programming language." }, { "code": null, "e": 25825, "s": 25672, "text": "This function is used to get the first column using slice operator. for the rows we extract all of them, for columns specify the index for first column." }, { "code": null, "e": 25834, "s": 25825, "text": "Syntax :" }, { "code": null, "e": 25855, "s": 25834, "text": "dataframe.iloc[:, 0]" }, { "code": null, "e": 25895, "s": 25855, "text": "where. dataframe is the input dataframe" }, { "code": null, "e": 25929, "s": 25895, "text": "The slice operation will be like:" }, { "code": null, "e": 25976, "s": 25929, "text": "[row_start:row_end , column_start, column_end]" }, { "code": null, "e": 25983, "s": 25976, "text": "where," }, { "code": null, "e": 26035, "s": 25983, "text": "row_start refers start row with 0 position as index" }, { "code": null, "e": 26088, "s": 26035, "text": "row_end refers last row with n th position as index" }, { "code": null, "e": 26146, "s": 26088, "text": "column_start refers start column with 0 position as index" }, { "code": null, "e": 26204, "s": 26146, "text": "column_end refers last column with n th position as index" }, { "code": null, "e": 26252, "s": 26204, "text": "The following alternative can also be employed." }, { "code": null, "e": 26261, "s": 26252, "text": "Syntax :" }, { "code": null, "e": 26283, "s": 26261, "text": "dataframe.iloc[:, :1]" }, { "code": null, "e": 26374, "s": 26283, "text": "where. dataframe is the input dataframe. Both of these will return the dataframe datatype." }, { "code": null, "e": 26448, "s": 26374, "text": "Example: Python program to get the first column by using above approaches" }, { "code": null, "e": 26456, "s": 26448, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print(\"--------------\") # get first column by returning seriesprint(data.iloc[:, 0]) print(\"--------------\") # get first column by returning dataframeprint(data.iloc[:, :1])", "e": 26911, "s": 26456, "text": null }, { "code": null, "e": 26919, "s": 26911, "text": "Output:" }, { "code": null, "e": 27016, "s": 26919, "text": "This method will return the column based on index. So, we have to give 0 to get the first column" }, { "code": null, "e": 27024, "s": 27016, "text": "Syntax:" }, { "code": null, "e": 27056, "s": 27024, "text": "dataframe[dataframe.columns[0]]" }, { "code": null, "e": 27062, "s": 27056, "text": "where" }, { "code": null, "e": 27095, "s": 27062, "text": "dataframe is the input dataframe" }, { "code": null, "e": 27129, "s": 27095, "text": "columns[0] represent first column" }, { "code": null, "e": 27193, "s": 27129, "text": "Example: Python program to get the first column using columns[]" }, { "code": null, "e": 27201, "s": 27193, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print(\"--------------\") # get first column by returning dataframe# using columns[] methodprint(data[data.columns[0]])", "e": 27600, "s": 27201, "text": null }, { "code": null, "e": 27608, "s": 27600, "text": "Output:" }, { "code": null, "e": 27666, "s": 27608, "text": "We can use the first column name to get the first column." }, { "code": null, "e": 27674, "s": 27666, "text": "Syntax:" }, { "code": null, "e": 27697, "s": 27674, "text": "dataframe.first_column" }, { "code": null, "e": 27760, "s": 27697, "text": "Example: Python code to get the first column using column name" }, { "code": null, "e": 27768, "s": 27760, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print(\"--------------\") # get first column by returning dataframe# using column_nameprint(data.id)", "e": 28148, "s": 27768, "text": null }, { "code": null, "e": 28156, "s": 28148, "text": "Output:" }, { "code": null, "e": 28255, "s": 28156, "text": "We can also use the head() function within this to display the number of rows in the first column." }, { "code": null, "e": 28322, "s": 28255, "text": "Example: Python code to get the first column using the column name" }, { "code": null, "e": 28330, "s": 28322, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print(\"--------------\") # get first column by returning dataframe# using column_name# display 1 rowprint(data.id.head(1))print(\"--------------\") # get first column by returning dataframe# using column_name# display 2 rowsprint(data.id.head(2))print(\"--------------\") # get first column by returning dataframe# using column_name# display 4 rowsprint(data.id.head(4))", "e": 28979, "s": 28330, "text": null }, { "code": null, "e": 28987, "s": 28979, "text": "Output:" }, { "code": null, "e": 29177, "s": 28987, "text": "This function by default returns the top rows of the dataframe. To return the column we have to Transpose (Interchange rows to columns) the dataframe by using T function and get 1st column." }, { "code": null, "e": 29185, "s": 29177, "text": "Syntax:" }, { "code": null, "e": 29207, "s": 29185, "text": "dataframe.T.head(1).T" }, { "code": null, "e": 29270, "s": 29207, "text": "Example: Python code to get the first column using column name" }, { "code": null, "e": 29278, "s": 29270, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"id\": [7058, 7059, 7072, 7054], \"name\": ['sravan', 'jyothika', 'harsha', 'ramya'], \"subjects\": ['java', 'python', 'html/php', 'php/js']}) # display dataframeprint(data) print(\"--------------\")# using headprint(data.T.head(1).T)", "e": 29615, "s": 29278, "text": null }, { "code": null, "e": 29623, "s": 29615, "text": "Output:" }, { "code": null, "e": 29648, "s": 29623, "text": "pandas-dataframe-program" }, { "code": null, "e": 29655, "s": 29648, "text": "Picked" }, { "code": null, "e": 29679, "s": 29655, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29693, "s": 29679, "text": "Python-pandas" }, { "code": null, "e": 29700, "s": 29693, "text": "Python" }, { "code": null, "e": 29798, "s": 29700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29830, "s": 29798, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29872, "s": 29830, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29914, "s": 29872, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29970, "s": 29914, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29997, "s": 29970, "text": "Python Classes and Objects" }, { "code": null, "e": 30028, "s": 29997, "text": "Python | os.path.join() method" }, { "code": null, "e": 30057, "s": 30028, "text": "Create a directory in Python" }, { "code": null, "e": 30079, "s": 30057, "text": "Defaultdict in Python" }, { "code": null, "e": 30118, "s": 30079, "text": "Python | Get unique values from a list" } ]
PyCairo- Drawing Function curve - GeeksforGeeks
23 Jan, 2022 In this article we will learn how we can draw a simple function curve using PyCairo in python. n mathematics, the graph of a function f is the set of ordered pairs, where f(x) = y. In the common case where x and f(x) are real numbers, these pairs are Cartesian coordinates of points in two-dimensional space. PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web. Steps of Implementation : Import the Pycairo & Math module.Create a SVG surface object and add context to it.Creating list for creating points for functional curveTraversing and plotting PointsSetting color of the context & line width Import the Pycairo & Math module. Create a SVG surface object and add context to it. Creating list for creating points for functional curve Traversing and plotting Points Setting color of the context & line width Below is the Implementation : Python3 # importing pycairoimport cairo# importing Math to Sin & exp Functionimport math # Variable Xx = 0# Creating list for creating pointspoints = []# Creating Loop for pointswhile x < 5: # Creating point corresponding x y = math.sin(10*x)*math.exp(-x/2) # Adding points to the list points.append((x*100 + 50, y*100 + 200)) # Incrementing by 0.01 Variable x x += 0.01 # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek95.svg", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) context.move_to(*points[0]) # Traversing Points for p in points[1:]: # Ploting point context.line_to(*p) # setting width of the context context.set_line_width(2) # setting color of the context context.set_source_rgb(0.2, 1, 0.2) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Output : saurabh1990aror Python-PyCairo Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n23 Jan, 2022" }, { "code": null, "e": 25974, "s": 25665, "text": "In this article we will learn how we can draw a simple function curve using PyCairo in python. n mathematics, the graph of a function f is the set of ordered pairs, where f(x) = y. In the common case where x and f(x) are real numbers, these pairs are Cartesian coordinates of points in two-dimensional space." }, { "code": null, "e": 26364, "s": 25974, "text": "PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. " }, { "code": null, "e": 26640, "s": 26364, "text": "SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web." }, { "code": null, "e": 26666, "s": 26640, "text": "Steps of Implementation :" }, { "code": null, "e": 26875, "s": 26666, "text": "Import the Pycairo & Math module.Create a SVG surface object and add context to it.Creating list for creating points for functional curveTraversing and plotting PointsSetting color of the context & line width" }, { "code": null, "e": 26909, "s": 26875, "text": "Import the Pycairo & Math module." }, { "code": null, "e": 26960, "s": 26909, "text": "Create a SVG surface object and add context to it." }, { "code": null, "e": 27015, "s": 26960, "text": "Creating list for creating points for functional curve" }, { "code": null, "e": 27046, "s": 27015, "text": "Traversing and plotting Points" }, { "code": null, "e": 27088, "s": 27046, "text": "Setting color of the context & line width" }, { "code": null, "e": 27118, "s": 27088, "text": "Below is the Implementation :" }, { "code": null, "e": 27126, "s": 27118, "text": "Python3" }, { "code": "# importing pycairoimport cairo# importing Math to Sin & exp Functionimport math # Variable Xx = 0# Creating list for creating pointspoints = []# Creating Loop for pointswhile x < 5: # Creating point corresponding x y = math.sin(10*x)*math.exp(-x/2) # Adding points to the list points.append((x*100 + 50, y*100 + 200)) # Incrementing by 0.01 Variable x x += 0.01 # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek95.svg\", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) context.move_to(*points[0]) # Traversing Points for p in points[1:]: # Ploting point context.line_to(*p) # setting width of the context context.set_line_width(2) # setting color of the context context.set_source_rgb(0.2, 1, 0.2) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 28143, "s": 27126, "text": null }, { "code": null, "e": 28152, "s": 28143, "text": "Output :" }, { "code": null, "e": 28168, "s": 28152, "text": "saurabh1990aror" }, { "code": null, "e": 28183, "s": 28168, "text": "Python-PyCairo" }, { "code": null, "e": 28190, "s": 28183, "text": "Python" }, { "code": null, "e": 28288, "s": 28190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28320, "s": 28288, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28362, "s": 28320, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28404, "s": 28362, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28460, "s": 28404, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28487, "s": 28460, "text": "Python Classes and Objects" }, { "code": null, "e": 28518, "s": 28487, "text": "Python | os.path.join() method" }, { "code": null, "e": 28547, "s": 28518, "text": "Create a directory in Python" }, { "code": null, "e": 28569, "s": 28547, "text": "Defaultdict in Python" }, { "code": null, "e": 28608, "s": 28569, "text": "Python | Get unique values from a list" } ]
Most frequent word in an array of strings | Practice | GeeksforGeeks
Given an array arr containing N words consisting of lowercase characters. Your task is to find the most frequent word in the array. If multiple words have same frequency, then print the word whose first occurence occurs last in the array as compared to the other strings with same frequency. Example 1: Input: N = 3 arr[] = {geeks,for,geeks} Output: geeks Explanation: "geeks" comes 2 times. Example 2: Input: N = 2 arr[] = {hello,world} Output: world Explanation: "hello" and "world" both have 1 frequency. We print world as its first occurence comes last in the input array. Your Task: Complete mostFrequentWord function which takes array of strings and its length as arguments and returns the most frequent word. The printing is done by the driver code. Expected Time Complexity: O(N * WORD_LEN). Expected Auxiliary Space: O(N * WORD_LEN). 0 vinamrajha3 weeks ago // this problem is supposed to be solved by using trie not by hashmap/unordered_map. struct trienode{ trienode *child[26]; int count; bool flag; int in; trienode(){ for(int i =0; i<26; ++i) child[i]= NULL; count =0; flag = false; } }; void insert(string s, trienode *root, int idx){ trienode *curr= root; for(int i =0; i<s.length(); ++i){ int index = s[i] -'a'; if(!curr->child[index]) curr->child[index] = new trienode(); curr = curr->child[index]; } curr->count++; if(!curr->flag){ curr->in = idx; curr->flag = true; } } trienode *search(string s, trienode *root){ trienode *curr = root; for(int i =0; i<s.length(); ++i){ int index = s[i]-'a'; curr = curr->child[index]; } return curr; } string mostFrequentWord(string arr[], int n) { // code here trienode *root = new trienode(); int maxi = INT_MIN; string ans; int idx; for(int i =0; i<n; ++i) insert(arr[i], root, i); for(int i =0; i<n; ++i){ trienode *curr = search(arr[i], root); if(maxi<curr->count){ maxi = curr->count; ans = arr[i]; idx = curr->in; }else if(maxi == curr->count){ if(idx<curr->in){ ans = arr[i]; idx = curr->in; } } } return ans; } 0 rajbhargavp1 month ago from collections import Counter as cclass Solution: #Function to find most frequent word in an array of strings. def mostFrequentWord(self,arr,n): # code here d=[] for i in range(n): if arr[i] not in d: d.append(arr[i]) a=c(arr) d.reverse() d.sort(key=lambda x:a[x] ,reverse=True) return d[0] +1 neeramrutia2 months ago int max=0; HashMap<String,Integer> hm=new HashMap<>(); int i; for(i=0;i<n;i++) { if(!hm.containsKey(arr[i])) { hm.put(arr[i],1); } else { hm.put(arr[i],hm.get(arr[i])+1); } } String ans=""; for(i=0;i<n;i++) { if(hm.get(arr[i])>=max) { max=hm.get(arr[i]); ans=arr[i]; hm.put(arr[i],0); } } return ans; 0 rahulagarwal11262 months ago Java Solution Runtime: 0.5s class pair{ String s; int index; pair(String s,int index){ this.s=s; this.index=index; } } class Solution { //Function to find most frequent word in an array of strings. public String mostFrequentWord(String arr[],int n) { Map<String,Integer>mp=new HashMap<>(); int maxcount=0; for(int i=0;i<n;i++){ mp.put(arr[i],mp.getOrDefault(arr[i],0)+1); // count the occurences of each String maxcount=Math.max(maxcount,mp.get(arr[i])); //maximum count among all occurences } PriorityQueue<pair>pq=new PriorityQueue<>(new Comparator<pair>(){ public int compare(pair a, pair b){ return b.index-a.index; //sorting accoring to maxindex } }); for(int i=0;i<n;i++){ if(mp.containsKey(arr[i]) && mp.get(arr[i])==maxcount){ pq.offer(new pair(arr[i],i)); mp.remove(arr[i]); } } return pq.poll().s; } } 0 neerajsingh130619993 months ago c++ O(n) simple solution using map string mostFrequentWord(string arr[], int n) { // code here vector<string> v; map<string,int> m; for(int i=0;i<n;i++) { if(m.count(arr[i])>0) m[arr[i]]++; else { m[arr[i]]=1; v.push_back(arr[i]); } } string s; int m1=0; for(int i=0;i<v.size();i++) { if(m[v[i]]>=m1) { s=v[i]; m1=m[v[i]]; } } return s; } 0 ag14715883 months ago Java Solution:- Runtime: 0.6 public static String mostFrequentWord(String arr[],int n) { HashMap<String,Integer> map = new HashMap<>(); for(int i=0; i<n; i++){ map.put(arr[i], map.getOrDefault(arr[i], 0)+1 ); } int max = Integer.MIN_VALUE; String s = ""; for(int i=0; i<n; i++){ if( map.get(arr[i]) >= max ){ max = map.get(arr[i]); s = arr[i]; map.put( arr[i],0 ); } } return s; } -1 kaditya213 months ago Java Solution:- class Solution{ //Function to find most frequent word in an array of strings. public String mostFrequentWord(String arr[],int n) { Trie trie = new Trie(); for(int i=0; i<n; i++){ trie.insert(arr[i],i); } for(String s: arr){ trie.mostFrequent(s); } return trie.mostFrequentWord; } } class Trie{ private class TrieNode{ TrieNode children []; boolean isEndWord; int count; int index = -1; TrieNode(){ children = new TrieNode[26]; isEndWord = false; count =0; } } String mostFrequentWord =""; int maxCount =Integer.MIN_VALUE; TrieNode root; Trie(){ root = new TrieNode(); } public void insert(String key, int position){ TrieNode pointer = root; for(int i=0; i<key.length(); i++){ int index = key.charAt(i) -'a'; if(pointer.children[index] == null){ pointer.children[index] = new TrieNode(); } pointer = pointer.children[index]; } pointer.isEndWord = true; pointer.count++; if(pointer.index == -1){ pointer.index =position; } if(maxCount < pointer.count){ maxCount = pointer.count; } } int idx =-1; public void mostFrequent(String key){ TrieNode pointer = root; for(int i=0; i<key.length(); i++){ int index = key.charAt(i) -'a'; if(pointer.children[index] == null){ pointer.children[index] = new TrieNode(); } pointer = pointer.children[index]; } if(pointer.count == maxCount && pointer.index>idx){ mostFrequentWord=key; idx = pointer.index; } } } +2 mr_coder99334 months ago //using unordered_map C++ 0.1 string mostFrequentWord(string arr[], int n) { unordered_map<string,int> m; for(int i=0;i<n;i++) { m[arr[i]]++; } int Max=INT_MIN; string s=""; for(int i=0;i<n;i++) { if(m[arr[i]]>=Max) { Max=m[arr[i]]; s=arr[i]; m[arr[i]]=0; } } return s; } +4 saiabhiteja5 months ago using trie data structure with functions 1.insert 2.countwordsequalto(frequency) 3.getting_start_index(for getting starting index) struct node{ node* links[26]; int endwith=0; int start_index = -1; node(){ for(int i = 0;i<26;i++){ links[i] = nullptr; } } bool iscontains(char ch){ //checking wether the charcter is already there are not return (links[ch-'a'] != NULL) ; } void put(char ch,node* Node){ links[ch-'a'] = Node ; } node* get(char ch){ //for getting particular link return links[ch-'a']; } void increaseend(){ endwith++; } void decreaseend(){ endwith--; } void set_start_index(int i){ start_index = i; } int getendswith(){ return endwith ; } int get_start_index(){ return start_index ; } };class trie{ private: node* root ; public: trie(){ //intilisation root = new node(); } void insert(string s,int ind){ //inserting function node* temp = root ; for(int i = 0;i<s.size();i++){ if(!temp->iscontains(s[i])){ temp->put(s[i],new node()); } temp = temp->get(s[i]); } temp->increaseend(); if(temp->get_start_index() == -1){ temp->set_start_index(ind) ; } } int countwordsequalto(string s){ //for getting frequency node* temp = root; for(int i = 0;i<s.size();i++){ if(!temp->get(s[i])){ return 0; } temp = temp->get(s[i]); } return temp->getendswith(); } int get_starting_index(string s){ //for getting starting index node* temp = root; for(int i = 0;i<s.size();i++){ if(!temp->get(s[i])){ return 0; } temp = temp->get(s[i]); } return temp->get_start_index(); }};class Solution{ public: //Function to find most frequent word in an array of strings. string mostFrequentWord(string arr[], int n) { trie t; for(int i = 0;i<n;i++){ t.insert(arr[i],i); } int fre = -1; string ans = ""; for(int i = 0;i<n;i++){ int x = t.countwordsequalto(arr[i]); int c = t.get_starting_index(arr[i]); if(x>fre){ fre = x; ans = arr[i]; } else if(x == fre){ // for getting last occurrence of same frequency int c2 = t.get_starting_index(ans); if(c>c2){ ans = arr[i]; } } } return ans; }}; 0 adarsh0086 months ago string mostFrequentWord(string arr[], int n) { // code here string res; unordered_map<string,int> freq; unordered_set<string> s; for(int i=0;i<n;i++) { freq[arr[i]]++; } res=arr[0]; int res_freq=freq[arr[0]]; s.insert(arr[0]); for(int i=1;i<n;i++) { if(freq[arr[i]]>=res_freq && s.find(arr[i])==s.end()) { res=arr[i]; res_freq=freq[arr[i]]; s.insert(arr[i]); } } return res; } 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": 530, "s": 238, "text": "Given an array arr containing N words consisting of lowercase characters. Your task is to find the most frequent word in the array. If multiple words have same frequency, then print the word whose first occurence occurs last in the array as compared to the other strings with same frequency." }, { "code": null, "e": 541, "s": 530, "text": "Example 1:" }, { "code": null, "e": 631, "s": 541, "text": "Input:\nN = 3\narr[] = {geeks,for,geeks}\nOutput: geeks\nExplanation: \"geeks\" comes 2 times.\n" }, { "code": null, "e": 642, "s": 631, "text": "Example 2:" }, { "code": null, "e": 816, "s": 642, "text": "Input:\nN = 2\narr[] = {hello,world}\nOutput: world\nExplanation: \"hello\" and \"world\" both\nhave 1 frequency. We print world as\nits first occurence comes last in the\ninput array." }, { "code": null, "e": 996, "s": 816, "text": "Your Task:\nComplete mostFrequentWord function which takes array of strings and its length as arguments and returns the most frequent word. The printing is done by the driver code." }, { "code": null, "e": 1082, "s": 996, "text": "Expected Time Complexity: O(N * WORD_LEN).\nExpected Auxiliary Space: O(N * WORD_LEN)." }, { "code": null, "e": 1084, "s": 1082, "text": "0" }, { "code": null, "e": 1106, "s": 1084, "text": "vinamrajha3 weeks ago" }, { "code": null, "e": 2650, "s": 1106, "text": "// this problem is supposed to be solved by using trie not by hashmap/unordered_map.\n\nstruct trienode{\n trienode *child[26];\n int count;\n bool flag;\n int in;\n trienode(){\n for(int i =0; i<26; ++i) child[i]= NULL;\n count =0;\n flag = false;\n }\n};\nvoid insert(string s, trienode *root, int idx){\n trienode *curr= root;\n for(int i =0; i<s.length(); ++i){\n int index = s[i] -'a';\n if(!curr->child[index]) curr->child[index] = new trienode();\n curr = curr->child[index];\n }\n curr->count++;\n if(!curr->flag){ \n curr->in = idx;\n curr->flag = true;\n }\n }\n \n trienode *search(string s, trienode *root){\n trienode *curr = root;\n for(int i =0; i<s.length(); ++i){\n int index = s[i]-'a';\n curr = curr->child[index];\n }\n return curr;\n }\n \n string mostFrequentWord(string arr[], int n) \n {\n // code here\n trienode *root = new trienode();\n int maxi = INT_MIN;\n string ans;\n int idx;\n for(int i =0; i<n; ++i) insert(arr[i], root, i);\n for(int i =0; i<n; ++i){\n trienode *curr = search(arr[i], root);\n if(maxi<curr->count){\n maxi = curr->count;\n ans = arr[i];\n idx = curr->in;\n }else if(maxi == curr->count){\n if(idx<curr->in){\n ans = arr[i];\n idx = curr->in;\n }\n }\n }\n return ans;\n }" }, { "code": null, "e": 2652, "s": 2650, "text": "0" }, { "code": null, "e": 2675, "s": 2652, "text": "rajbhargavp1 month ago" }, { "code": null, "e": 3048, "s": 2675, "text": "from collections import Counter as cclass Solution: #Function to find most frequent word in an array of strings. def mostFrequentWord(self,arr,n): # code here d=[] for i in range(n): if arr[i] not in d: d.append(arr[i]) a=c(arr) d.reverse() d.sort(key=lambda x:a[x] ,reverse=True) return d[0] " }, { "code": null, "e": 3051, "s": 3048, "text": "+1" }, { "code": null, "e": 3075, "s": 3051, "text": "neeramrutia2 months ago" }, { "code": null, "e": 3598, "s": 3075, "text": "int max=0; HashMap<String,Integer> hm=new HashMap<>(); int i; for(i=0;i<n;i++) { if(!hm.containsKey(arr[i])) { hm.put(arr[i],1); } else { hm.put(arr[i],hm.get(arr[i])+1); } } String ans=\"\"; for(i=0;i<n;i++) { if(hm.get(arr[i])>=max) { max=hm.get(arr[i]); ans=arr[i]; hm.put(arr[i],0); } } return ans;" }, { "code": null, "e": 3600, "s": 3598, "text": "0" }, { "code": null, "e": 3629, "s": 3600, "text": "rahulagarwal11262 months ago" }, { "code": null, "e": 3644, "s": 3629, "text": "Java Solution " }, { "code": null, "e": 3658, "s": 3644, "text": "Runtime: 0.5s" }, { "code": null, "e": 4695, "s": 3658, "text": "class pair{\n String s;\n int index;\n pair(String s,int index){\n this.s=s;\n this.index=index; \n }\n}\n\nclass Solution\n{\n //Function to find most frequent word in an array of strings.\n public String mostFrequentWord(String arr[],int n)\n {\n Map<String,Integer>mp=new HashMap<>();\n int maxcount=0;\n for(int i=0;i<n;i++){\n mp.put(arr[i],mp.getOrDefault(arr[i],0)+1); // count the occurences of each String\n maxcount=Math.max(maxcount,mp.get(arr[i])); //maximum count among all occurences\n }\n PriorityQueue<pair>pq=new PriorityQueue<>(new Comparator<pair>(){\n public int compare(pair a, pair b){\n return b.index-a.index; //sorting accoring to maxindex\n }\n }); \n for(int i=0;i<n;i++){\n if(mp.containsKey(arr[i]) && mp.get(arr[i])==maxcount){\n pq.offer(new pair(arr[i],i));\n mp.remove(arr[i]);\n }\n }\n return pq.poll().s;\n \n }\n\n}" }, { "code": null, "e": 4697, "s": 4695, "text": "0" }, { "code": null, "e": 4729, "s": 4697, "text": "neerajsingh130619993 months ago" }, { "code": null, "e": 4764, "s": 4729, "text": "c++ O(n) simple solution using map" }, { "code": null, "e": 5273, "s": 4764, "text": "string mostFrequentWord(string arr[], int n) { // code here vector<string> v; map<string,int> m; for(int i=0;i<n;i++) { if(m.count(arr[i])>0) m[arr[i]]++; else { m[arr[i]]=1; v.push_back(arr[i]); } } string s; int m1=0; for(int i=0;i<v.size();i++) { if(m[v[i]]>=m1) { s=v[i]; m1=m[v[i]]; } } return s; }" }, { "code": null, "e": 5275, "s": 5273, "text": "0" }, { "code": null, "e": 5297, "s": 5275, "text": "ag14715883 months ago" }, { "code": null, "e": 5314, "s": 5297, "text": "Java Solution:- " }, { "code": null, "e": 5327, "s": 5314, "text": "Runtime: 0.6" }, { "code": null, "e": 5845, "s": 5329, "text": "public static String mostFrequentWord(String arr[],int n)\n {\n HashMap<String,Integer> map = new HashMap<>();\n \n for(int i=0; i<n; i++){\n map.put(arr[i], map.getOrDefault(arr[i], 0)+1 );\n }\n \n int max = Integer.MIN_VALUE;\n String s = \"\";\n \n for(int i=0; i<n; i++){\n if( map.get(arr[i]) >= max ){\n max = map.get(arr[i]);\n s = arr[i];\n map.put( arr[i],0 );\n }\n }\n return s;\n }" }, { "code": null, "e": 5850, "s": 5847, "text": "-1" }, { "code": null, "e": 5872, "s": 5850, "text": "kaditya213 months ago" }, { "code": null, "e": 5888, "s": 5872, "text": "Java Solution:-" }, { "code": null, "e": 6251, "s": 5890, "text": "class Solution{ //Function to find most frequent word in an array of strings. public String mostFrequentWord(String arr[],int n) { Trie trie = new Trie(); for(int i=0; i<n; i++){ trie.insert(arr[i],i); } for(String s: arr){ trie.mostFrequent(s); } return trie.mostFrequentWord; } " }, { "code": null, "e": 6253, "s": 6251, "text": "}" }, { "code": null, "e": 7722, "s": 6253, "text": "class Trie{ private class TrieNode{ TrieNode children []; boolean isEndWord; int count; int index = -1; TrieNode(){ children = new TrieNode[26]; isEndWord = false; count =0; } } String mostFrequentWord =\"\"; int maxCount =Integer.MIN_VALUE; TrieNode root; Trie(){ root = new TrieNode(); } public void insert(String key, int position){ TrieNode pointer = root; for(int i=0; i<key.length(); i++){ int index = key.charAt(i) -'a'; if(pointer.children[index] == null){ pointer.children[index] = new TrieNode(); } pointer = pointer.children[index]; } pointer.isEndWord = true; pointer.count++; if(pointer.index == -1){ pointer.index =position; } if(maxCount < pointer.count){ maxCount = pointer.count; } } int idx =-1; public void mostFrequent(String key){ TrieNode pointer = root; for(int i=0; i<key.length(); i++){ int index = key.charAt(i) -'a'; if(pointer.children[index] == null){ pointer.children[index] = new TrieNode(); } pointer = pointer.children[index]; } if(pointer.count == maxCount && pointer.index>idx){ mostFrequentWord=key; idx = pointer.index; } } } " }, { "code": null, "e": 7725, "s": 7722, "text": "+2" }, { "code": null, "e": 7750, "s": 7725, "text": "mr_coder99334 months ago" }, { "code": null, "e": 8208, "s": 7750, "text": "//using unordered_map C++ 0.1\nstring mostFrequentWord(string arr[], int n) \n {\n unordered_map<string,int> m;\n for(int i=0;i<n;i++)\n {\n m[arr[i]]++;\n }\n int Max=INT_MIN;\n string s=\"\";\n for(int i=0;i<n;i++)\n {\n \tif(m[arr[i]]>=Max)\n {\n Max=m[arr[i]];\n s=arr[i];\n m[arr[i]]=0; \n }\n }\n return s;\n }" }, { "code": null, "e": 8211, "s": 8208, "text": "+4" }, { "code": null, "e": 8235, "s": 8211, "text": "saiabhiteja5 months ago" }, { "code": null, "e": 8261, "s": 8235, "text": "using trie data structure" }, { "code": null, "e": 8276, "s": 8261, "text": "with functions" }, { "code": null, "e": 8285, "s": 8276, "text": "1.insert" }, { "code": null, "e": 8316, "s": 8285, "text": "2.countwordsequalto(frequency)" }, { "code": null, "e": 8366, "s": 8316, "text": "3.getting_start_index(for getting starting index)" }, { "code": null, "e": 8441, "s": 8368, "text": "struct node{ node* links[26]; int endwith=0; int start_index = -1;" }, { "code": null, "e": 8525, "s": 8441, "text": " node(){ for(int i = 0;i<26;i++){ links[i] = nullptr; } }" }, { "code": null, "e": 8655, "s": 8525, "text": " bool iscontains(char ch){ //checking wether the charcter is already there are not return (links[ch-'a'] != NULL) ;" }, { "code": null, "e": 8660, "s": 8655, "text": " }" }, { "code": null, "e": 8726, "s": 8660, "text": " void put(char ch,node* Node){ links[ch-'a'] = Node ; }" }, { "code": null, "e": 8818, "s": 8726, "text": " node* get(char ch){ //for getting particular link return links[ch-'a']; }" }, { "code": null, "e": 9076, "s": 8818, "text": " void increaseend(){ endwith++; } void decreaseend(){ endwith--; } void set_start_index(int i){ start_index = i; } int getendswith(){ return endwith ; } int get_start_index(){ return start_index ; }" }, { "code": null, "e": 9186, "s": 9076, "text": "};class trie{ private: node* root ; public: trie(){ //intilisation root = new node(); }" }, { "code": null, "e": 9564, "s": 9186, "text": " void insert(string s,int ind){ //inserting function node* temp = root ; for(int i = 0;i<s.size();i++){ if(!temp->iscontains(s[i])){ temp->put(s[i],new node()); } temp = temp->get(s[i]); } temp->increaseend(); if(temp->get_start_index() == -1){ temp->set_start_index(ind) ; } }" }, { "code": null, "e": 10627, "s": 9564, "text": " int countwordsequalto(string s){ //for getting frequency node* temp = root; for(int i = 0;i<s.size();i++){ if(!temp->get(s[i])){ return 0; } temp = temp->get(s[i]); } return temp->getendswith(); } int get_starting_index(string s){ //for getting starting index node* temp = root; for(int i = 0;i<s.size();i++){ if(!temp->get(s[i])){ return 0; } temp = temp->get(s[i]); } return temp->get_start_index(); }};class Solution{ public: //Function to find most frequent word in an array of strings. string mostFrequentWord(string arr[], int n) { trie t; for(int i = 0;i<n;i++){ t.insert(arr[i],i); } int fre = -1; string ans = \"\"; for(int i = 0;i<n;i++){ int x = t.countwordsequalto(arr[i]); int c = t.get_starting_index(arr[i]); if(x>fre){ fre = x; ans = arr[i]; } else if(x == fre){" }, { "code": null, "e": 10835, "s": 10627, "text": "// for getting last occurrence of same frequency int c2 = t.get_starting_index(ans); if(c>c2){ ans = arr[i]; } } } return ans; }};" }, { "code": null, "e": 10837, "s": 10835, "text": "0" }, { "code": null, "e": 10859, "s": 10837, "text": "adarsh0086 months ago" }, { "code": null, "e": 11435, "s": 10859, "text": "string mostFrequentWord(string arr[], int n) { // code here string res; unordered_map<string,int> freq; unordered_set<string> s; for(int i=0;i<n;i++) { freq[arr[i]]++; } res=arr[0]; int res_freq=freq[arr[0]]; s.insert(arr[0]); for(int i=1;i<n;i++) { if(freq[arr[i]]>=res_freq && s.find(arr[i])==s.end()) { res=arr[i]; res_freq=freq[arr[i]]; s.insert(arr[i]); } } return res; }" }, { "code": null, "e": 11581, "s": 11435, "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": 11617, "s": 11581, "text": " Login to access your submissions. " }, { "code": null, "e": 11627, "s": 11617, "text": "\nProblem\n" }, { "code": null, "e": 11637, "s": 11627, "text": "\nContest\n" }, { "code": null, "e": 11700, "s": 11637, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11848, "s": 11700, "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": 12056, "s": 11848, "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": 12162, "s": 12056, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
What is use of $error variable in PowerShell?
Error variable in PowerShell is to view the errors generated in the current PowerShell session. We can say that the $Error variable is the container that stores all the errors and the latest error will be displayed first. For the example below, we will set the $Errorview to Category view to minimizing the error display content. By default $ErrorView is a Normal view. $ErrorView = "Categoryview" Now we will see the $error variable example, PS C:\WINDOWS\system32> asdds ObjectNotFound: (asdds:String) [], CommandNotFoundException PS C:\WINDOWS\system32> Get-process asddsd ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException Here, there is one wrong command and one wrong input we have written so let see what $error variable contains. PS C:\WINDOWS\system32> $error ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException ObjectNotFound: (asdds:String) [], CommandNotFoundException In the above output, the last error will be displayed first, and so on. $Errorvariable has become an array now. You can get the individual output as an array typical method. PS C:\WINDOWS\system32> $error[0] ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException PS C:\WINDOWS\system32> $error[1] ObjectNotFound: (asdds:String) [], CommandNotFoundException To get the count of errors generated, PS C:\WINDOWS\system32> $error.Count 2 To check the error capacity, you can run the below command. PS C:\WINDOWS\system32> $error.Capacity 4 When the capacity of storing error reaches 4, again this variable automatically increases its capacity by 4, so the total capacity becomes 8. So every time the error variable reaches its capacity, it increases the capacity by 4. For example, We already created 4 errors here, PS C:\WINDOWS\system32> $error ObjectNotFound: (221dsd:String) [], CommandNotFoundException ObjectNotFound: (7sdse:String) [], CommandNotFoundException ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException ObjectNotFound: (asdds:String) [], CommandNotFoundException When you add one more error count, PS C:\WINDOWS\system32> 5look ObjectNotFound: (5look:String) [], CommandNotFoundException Now check the capacity, PS C:\WINDOWS\system32> $error.Capacity 8 And the output, PS C:\WINDOWS\system32> $error ObjectNotFound: (5look:String) [], CommandNotFoundException ObjectNotFound: (221dsd:String) [], CommandNotFoundException ObjectNotFound: (7sdse:String) [], CommandNotFoundException ObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException ObjectNotFound: (asdds:String) [], CommandNotFoundException So question is, what is the threshold for this error variable capacity? To check it, you need to use the command $MaximumErrorCount. PS C:\WINDOWS\system32> $MaximumErrorCount 256 Here, the limit of the maximum error count is 256.
[ { "code": null, "e": 1432, "s": 1062, "text": "Error variable in PowerShell is to view the errors generated in the current PowerShell session. We can say that the $Error variable is the container that stores all the errors and the latest error will be displayed first. For the example below, we will set the $Errorview to Category view to minimizing the error display content. By default $ErrorView is a Normal view." }, { "code": null, "e": 1460, "s": 1432, "text": "$ErrorView = \"Categoryview\"" }, { "code": null, "e": 1505, "s": 1460, "text": "Now we will see the $error variable example," }, { "code": null, "e": 1709, "s": 1505, "text": "PS C:\\WINDOWS\\system32> asdds\nObjectNotFound: (asdds:String) [], CommandNotFoundException\nPS C:\\WINDOWS\\system32> Get-process asddsd\nObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException" }, { "code": null, "e": 1820, "s": 1709, "text": "Here, there is one wrong command and one wrong input we have written so let see what $error variable contains." }, { "code": null, "e": 1982, "s": 1820, "text": "PS C:\\WINDOWS\\system32> $error\nObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException\nObjectNotFound: (asdds:String) [], CommandNotFoundException" }, { "code": null, "e": 2156, "s": 1982, "text": "In the above output, the last error will be displayed first, and so on. $Errorvariable has become an array now. You can get the individual output as an array typical method." }, { "code": null, "e": 2355, "s": 2156, "text": "PS C:\\WINDOWS\\system32> $error[0]\nObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException\nPS C:\\WINDOWS\\system32> $error[1] ObjectNotFound: (asdds:String) [], CommandNotFoundException" }, { "code": null, "e": 2393, "s": 2355, "text": "To get the count of errors generated," }, { "code": null, "e": 2432, "s": 2393, "text": "PS C:\\WINDOWS\\system32> $error.Count\n2" }, { "code": null, "e": 2492, "s": 2432, "text": "To check the error capacity, you can run the below command." }, { "code": null, "e": 2534, "s": 2492, "text": "PS C:\\WINDOWS\\system32> $error.Capacity\n4" }, { "code": null, "e": 2763, "s": 2534, "text": "When the capacity of storing error reaches 4, again this variable automatically increases its capacity by 4, so the total capacity becomes 8. So every time the error variable reaches its capacity, it increases the capacity by 4." }, { "code": null, "e": 2776, "s": 2763, "text": "For example," }, { "code": null, "e": 2810, "s": 2776, "text": "We already created 4 errors here," }, { "code": null, "e": 3093, "s": 2810, "text": "PS C:\\WINDOWS\\system32> $error\nObjectNotFound: (221dsd:String) [], CommandNotFoundException\nObjectNotFound: (7sdse:String) [], CommandNotFoundException\nObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException\nObjectNotFound: (asdds:String) [], CommandNotFoundException" }, { "code": null, "e": 3128, "s": 3093, "text": "When you add one more error count," }, { "code": null, "e": 3218, "s": 3128, "text": "PS C:\\WINDOWS\\system32> 5look\nObjectNotFound: (5look:String) [], CommandNotFoundException" }, { "code": null, "e": 3242, "s": 3218, "text": "Now check the capacity," }, { "code": null, "e": 3284, "s": 3242, "text": "PS C:\\WINDOWS\\system32> $error.Capacity\n8" }, { "code": null, "e": 3300, "s": 3284, "text": "And the output," }, { "code": null, "e": 3643, "s": 3300, "text": "PS C:\\WINDOWS\\system32> $error\nObjectNotFound: (5look:String) [], CommandNotFoundException\nObjectNotFound: (221dsd:String) [], CommandNotFoundException\nObjectNotFound: (7sdse:String) [], CommandNotFoundException\nObjectNotFound: (asddsd:String) [Get-Process], ProcessCommandException\nObjectNotFound: (asdds:String) [], CommandNotFoundException" }, { "code": null, "e": 3776, "s": 3643, "text": "So question is, what is the threshold for this error variable capacity? To check it, you need to use the command $MaximumErrorCount." }, { "code": null, "e": 3823, "s": 3776, "text": "PS C:\\WINDOWS\\system32> $MaximumErrorCount\n256" }, { "code": null, "e": 3874, "s": 3823, "text": "Here, the limit of the maximum error count is 256." } ]
Convert a number to a string in JavaScript - GeeksforGeeks
05 Mar, 2021 In JavaScript, you can change any number into string format using the following methods. 1. Using toString(): This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type. Syntax: num.toString(); Example:JavascriptJavascript<script> let a = 20; console.log(a.toString()); console.log((50).toString()); console.log((60).toString()); console.log((7).toString(2)); // (7 in base 2, or binary)</script>Output:20 50 60 111 Example: Javascript <script> let a = 20; console.log(a.toString()); console.log((50).toString()); console.log((60).toString()); console.log((7).toString(2)); // (7 in base 2, or binary)</script> Output: 20 50 60 111 2. Using String() function: This method accepts an integer or floating-point number as a parameter and converts it into string type. Syntax: String(object); Example:JavascriptJavascript<script> let a = 30; console.log(String(a)); console.log(String(52)); console.log(String(35.64));</script>Output:30 52 35.64 Example: Javascript <script> let a = 30; console.log(String(a)); console.log(String(52)); console.log(String(35.64));</script> Output: 30 52 35.64 Note: It does not do any base conversations as .toString() does. 3. Concatenating an empty string: This is arguably one of the easiest ways to convert any integer or floating-point number into a string. Syntax: let variable_name =' ' + value; Example:JavascriptJavascript<script> let a = '' + 50; console.log(a);</script>Output:50 Example: Javascript <script> let a = '' + 50; console.log(a);</script> Output: 50 4.Template Strings: Injecting a number inside a String is also a valid way of parsing an Integer data type or Float data type. Syntax: let variable_name = '${value}'; Example:JavascriptJavascript<script> let num = 50; let flt = 50.205; let string = "${num}"; let floatString = "${flt}"; console.log(string); console.log(floatString);</script>Output:50 50.205 Example: Javascript <script> let num = 50; let flt = 50.205; let string = "${num}"; let floatString = "${flt}"; console.log(string); console.log(floatString);</script> Output: 50 50.205 The above 4 methods can be used to convert any integer or floating-point number into a string. JavaScript-Questions javascript-string JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Hide or show elements in HTML using display property Difference Between PUT and PATCH Request JavaScript | console.log() with Examples
[ { "code": null, "e": 37968, "s": 37940, "text": "\n05 Mar, 2021" }, { "code": null, "e": 38057, "s": 37968, "text": "In JavaScript, you can change any number into string format using the following methods." }, { "code": null, "e": 38213, "s": 38057, "text": "1. Using toString(): This method belongs to the Number.Prototype object. It takes an integer or a floating-point number and converts it into a string type." }, { "code": null, "e": 38221, "s": 38213, "text": "Syntax:" }, { "code": null, "e": 38237, "s": 38221, "text": "num.toString();" }, { "code": null, "e": 38466, "s": 38237, "text": "Example:JavascriptJavascript<script> let a = 20; console.log(a.toString()); console.log((50).toString()); console.log((60).toString()); console.log((7).toString(2)); // (7 in base 2, or binary)</script>Output:20\n50\n60\n111" }, { "code": null, "e": 38475, "s": 38466, "text": "Example:" }, { "code": null, "e": 38486, "s": 38475, "text": "Javascript" }, { "code": "<script> let a = 20; console.log(a.toString()); console.log((50).toString()); console.log((60).toString()); console.log((7).toString(2)); // (7 in base 2, or binary)</script>", "e": 38668, "s": 38486, "text": null }, { "code": null, "e": 38676, "s": 38668, "text": "Output:" }, { "code": null, "e": 38689, "s": 38676, "text": "20\n50\n60\n111" }, { "code": null, "e": 38822, "s": 38689, "text": "2. Using String() function: This method accepts an integer or floating-point number as a parameter and converts it into string type." }, { "code": null, "e": 38830, "s": 38822, "text": "Syntax:" }, { "code": null, "e": 38846, "s": 38830, "text": "String(object);" }, { "code": null, "e": 39005, "s": 38846, "text": "Example:JavascriptJavascript<script> let a = 30; console.log(String(a)); console.log(String(52)); console.log(String(35.64));</script>Output:30\n52\n35.64" }, { "code": null, "e": 39014, "s": 39005, "text": "Example:" }, { "code": null, "e": 39025, "s": 39014, "text": "Javascript" }, { "code": "<script> let a = 30; console.log(String(a)); console.log(String(52)); console.log(String(35.64));</script>", "e": 39138, "s": 39025, "text": null }, { "code": null, "e": 39146, "s": 39138, "text": "Output:" }, { "code": null, "e": 39158, "s": 39146, "text": "30\n52\n35.64" }, { "code": null, "e": 39223, "s": 39158, "text": "Note: It does not do any base conversations as .toString() does." }, { "code": null, "e": 39361, "s": 39223, "text": "3. Concatenating an empty string: This is arguably one of the easiest ways to convert any integer or floating-point number into a string." }, { "code": null, "e": 39369, "s": 39361, "text": "Syntax:" }, { "code": null, "e": 39401, "s": 39369, "text": "let variable_name =' ' + value;" }, { "code": null, "e": 39491, "s": 39401, "text": "Example:JavascriptJavascript<script> let a = '' + 50; console.log(a);</script>Output:50" }, { "code": null, "e": 39500, "s": 39491, "text": "Example:" }, { "code": null, "e": 39511, "s": 39500, "text": "Javascript" }, { "code": "<script> let a = '' + 50; console.log(a);</script>", "e": 39564, "s": 39511, "text": null }, { "code": null, "e": 39572, "s": 39564, "text": "Output:" }, { "code": null, "e": 39575, "s": 39572, "text": "50" }, { "code": null, "e": 39702, "s": 39575, "text": "4.Template Strings: Injecting a number inside a String is also a valid way of parsing an Integer data type or Float data type." }, { "code": null, "e": 39710, "s": 39702, "text": "Syntax:" }, { "code": null, "e": 39742, "s": 39710, "text": "let variable_name = '${value}';" }, { "code": null, "e": 39940, "s": 39742, "text": "Example:JavascriptJavascript<script> let num = 50; let flt = 50.205; let string = \"${num}\"; let floatString = \"${flt}\"; console.log(string); console.log(floatString);</script>Output:50\n50.205" }, { "code": null, "e": 39949, "s": 39940, "text": "Example:" }, { "code": null, "e": 39960, "s": 39949, "text": "Javascript" }, { "code": "<script> let num = 50; let flt = 50.205; let string = \"${num}\"; let floatString = \"${flt}\"; console.log(string); console.log(floatString);</script>", "e": 40114, "s": 39960, "text": null }, { "code": null, "e": 40122, "s": 40114, "text": "Output:" }, { "code": null, "e": 40132, "s": 40122, "text": "50\n50.205" }, { "code": null, "e": 40227, "s": 40132, "text": "The above 4 methods can be used to convert any integer or floating-point number into a string." }, { "code": null, "e": 40248, "s": 40227, "text": "JavaScript-Questions" }, { "code": null, "e": 40266, "s": 40248, "text": "javascript-string" }, { "code": null, "e": 40277, "s": 40266, "text": "JavaScript" }, { "code": null, "e": 40375, "s": 40277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40384, "s": 40375, "text": "Comments" }, { "code": null, "e": 40397, "s": 40384, "text": "Old Comments" }, { "code": null, "e": 40442, "s": 40397, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40511, "s": 40442, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40572, "s": 40511, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40644, "s": 40572, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40671, "s": 40644, "text": "File uploading in React.js" }, { "code": null, "e": 40723, "s": 40671, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 40769, "s": 40723, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 40822, "s": 40769, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 40863, "s": 40822, "text": "Difference Between PUT and PATCH Request" } ]
AutoCompleteTextView in Kotlin - GeeksforGeeks
28 Mar, 2022 Android AutoCompleteTextView is an editable text view which shows a list of suggestions when user starts typing text. When a user starts typing, a dropdown menu will be there based on the entered characters, defined in the threshold limit and the user can choose an item from the list to replace the text. The AutoCompleteTextView is a subclass of EditText class so we can easily inherit all the properties of EditText as per our requirements. The dropdown list will be obtained using the data adaptor and these suggestions will be appeared only after entering the minimum number of characters defined in the Threshold limit. The Threshold limit is used to define the minimum number of characters the user must type to see the dropdown list of suggestions. In android, we can create an AutoCompleteTextView control in two ways either manually in an XML file or create it in the Activity file programmatically. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we will add the AutoCompleteTextView and Button widget and set their attributes so that it can be accessed in the kotlin file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity="center"> <AutoCompleteTextView android:id="@+id/autoTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:hint="@string/hint"/> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/submit"/> </LinearLayout> Here, we will specify the name of the activity and define other strings which can be used at different places in our activity. Another important thing is that we will define string_array which contains the items for the suggestion list of AutoCompleteTextView. XML <resources> <string name="app_name">AutoCompleteTextViewInKotlin</string> <string name="hint">Please type language...</string> <string name="submit">Submit</string> <string name="submitted_lang">Submitted language:</string> <string-array name="Languages"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> <item>Javascript</item> <item>Jquery</item> </string-array> </resources> First of all, we declare a variable autotextview to access the widget from the XML layout. val autotextView = findViewById<AutoCompleteTextView>(R.id.autoTextView) then, we declare another variable languages to get the items of the string-array from the strings.xml file. val languages = resources.getStringArray(R.array.Languages) Create an adaptor and add into the AutoCompleteTextView of LinearLayout using val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) We are familiar with further activities in previous articles like accessing button and set OnClickListener etc. Kotlin package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val autotextView = findViewById<AutoCompleteTextView>(R.id.autoTextView) // Get the array of languages val languages = resources.getStringArray(R.array.Languages) // Create adapter and add in AutoCompleteTextView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) val button = findViewById<Button>(R.id.btn) if (button != null) { button ?.setOnClickListener(View.OnClickListener { val enteredText = getString(R.string.submitted_lang) + " " + autotextView.getText() Toast.makeText(this @MainActivity, enteredText, Toast.LENGTH_SHORT).show() }) } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http:// schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest> arunkrishnakv ayushpandey3july Android-View Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 23992, "s": 23964, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24298, "s": 23992, "text": "Android AutoCompleteTextView is an editable text view which shows a list of suggestions when user starts typing text. When a user starts typing, a dropdown menu will be there based on the entered characters, defined in the threshold limit and the user can choose an item from the list to replace the text." }, { "code": null, "e": 24436, "s": 24298, "text": "The AutoCompleteTextView is a subclass of EditText class so we can easily inherit all the properties of EditText as per our requirements." }, { "code": null, "e": 24749, "s": 24436, "text": "The dropdown list will be obtained using the data adaptor and these suggestions will be appeared only after entering the minimum number of characters defined in the Threshold limit. The Threshold limit is used to define the minimum number of characters the user must type to see the dropdown list of suggestions." }, { "code": null, "e": 24902, "s": 24749, "text": "In android, we can create an AutoCompleteTextView control in two ways either manually in an XML file or create it in the Activity file programmatically." }, { "code": null, "e": 24962, "s": 24902, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 25171, "s": 24962, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 25211, "s": 25171, "text": "Click on File, then New => New Project." }, { "code": null, "e": 25268, "s": 25211, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 25333, "s": 25268, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 25383, "s": 25333, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 25524, "s": 25383, "text": "In this file, we will add the AutoCompleteTextView and Button widget and set their attributes so that it can be accessed in the kotlin file." }, { "code": null, "e": 25528, "s": 25524, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity=\"center\"> <AutoCompleteTextView android:id=\"@+id/autoTextView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:hint=\"@string/hint\"/> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"@string/submit\"/> </LinearLayout>", "e": 26227, "s": 25528, "text": null }, { "code": null, "e": 26488, "s": 26227, "text": "Here, we will specify the name of the activity and define other strings which can be used at different places in our activity. Another important thing is that we will define string_array which contains the items for the suggestion list of AutoCompleteTextView." }, { "code": null, "e": 26492, "s": 26488, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">AutoCompleteTextViewInKotlin</string> <string name=\"hint\">Please type language...</string> <string name=\"submit\">Submit</string> <string name=\"submitted_lang\">Submitted language:</string> <string-array name=\"Languages\"> <item>Java</item> <item>Kotlin</item> <item>Swift</item> <item>Python</item> <item>Scala</item> <item>Perl</item> <item>Javascript</item> <item>Jquery</item> </string-array> </resources>", "e": 27012, "s": 26492, "text": null }, { "code": null, "e": 27103, "s": 27012, "text": "First of all, we declare a variable autotextview to access the widget from the XML layout." }, { "code": null, "e": 27176, "s": 27103, "text": "val autotextView = findViewById<AutoCompleteTextView>(R.id.autoTextView)" }, { "code": null, "e": 27284, "s": 27176, "text": "then, we declare another variable languages to get the items of the string-array from the strings.xml file." }, { "code": null, "e": 27344, "s": 27284, "text": "val languages = resources.getStringArray(R.array.Languages)" }, { "code": null, "e": 27422, "s": 27344, "text": "Create an adaptor and add into the AutoCompleteTextView of LinearLayout using" }, { "code": null, "e": 27552, "s": 27422, "text": "val adapter = ArrayAdapter(this,\n android.R.layout.simple_list_item_1, languages)\n autotextView.setAdapter(adapter)\n" }, { "code": null, "e": 27664, "s": 27552, "text": "We are familiar with further activities in previous articles like accessing button and set OnClickListener etc." }, { "code": null, "e": 27671, "s": 27664, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Button import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val autotextView = findViewById<AutoCompleteTextView>(R.id.autoTextView) // Get the array of languages val languages = resources.getStringArray(R.array.Languages) // Create adapter and add in AutoCompleteTextView val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, languages) autotextView.setAdapter(adapter) val button = findViewById<Button>(R.id.btn) if (button != null) { button ?.setOnClickListener(View.OnClickListener { val enteredText = getString(R.string.submitted_lang) + \" \" + autotextView.getText() Toast.makeText(this @MainActivity, enteredText, Toast.LENGTH_SHORT).show() }) } }}", "e": 29009, "s": 27671, "text": null }, { "code": null, "e": 29013, "s": 29009, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http:// schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 29669, "s": 29013, "text": null }, { "code": null, "e": 29685, "s": 29671, "text": "arunkrishnakv" }, { "code": null, "e": 29702, "s": 29685, "text": "ayushpandey3july" }, { "code": null, "e": 29715, "s": 29702, "text": "Android-View" }, { "code": null, "e": 29730, "s": 29715, "text": "Kotlin Android" }, { "code": null, "e": 29738, "s": 29730, "text": "Android" }, { "code": null, "e": 29745, "s": 29738, "text": "Kotlin" }, { "code": null, "e": 29753, "s": 29745, "text": "Android" }, { "code": null, "e": 29851, "s": 29753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29860, "s": 29851, "text": "Comments" }, { "code": null, "e": 29873, "s": 29860, "text": "Old Comments" }, { "code": null, "e": 29931, "s": 29873, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29974, "s": 29931, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30007, "s": 29974, "text": "Services in Android with Example" }, { "code": null, "e": 30049, "s": 30007, "text": "Content Providers in Android with Example" }, { "code": null, "e": 30080, "s": 30049, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 30123, "s": 30080, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30156, "s": 30123, "text": "Services in Android with Example" }, { "code": null, "e": 30198, "s": 30156, "text": "Content Providers in Android with Example" } ]
Check whether a given number is Polydivisible or Not - GeeksforGeeks
22 Feb, 2022 Given an integer n, find whether n is a Polydivisible or not. In mathematics, a number is called Polydivisible if it follows some unique properties. The number should not have any leading zeroes. The number formed by first i digits of the input number should be divisible by i, where . If any number follow these properties then it is called Polydivisible number. Examples: Input: 345654 Output: 345654 is Polydivisible number. Explanation: The first digit of the number is non-zero. The number formed by the first 2 digits(34) is divisible by 2. The number formed by the first 3 digits(345) is divisible by 3. The number formed by the first 4 digits(3456) is divisible by 4. The number formed by the first 5 digits(34565) is divisible by 5. The number formed by the first 6 digits(345654) is divisible by 6. Input: 130 Output: 130 is Not Polydivisible number. Input: 129 Output: 129 is Polydivisible number. Approach: The idea is very simple. Extract all the digits of the array and store them in an array.Pick first 2 digits and form a number and check if it is divisible by 2.Pick ith digit and append to the existing number and check if the number is divisible by i.If all the above conditions are satisfied until all the digits are exhausted,then the given number is Polydivisible. Extract all the digits of the array and store them in an array. Pick first 2 digits and form a number and check if it is divisible by 2. Pick ith digit and append to the existing number and check if the number is divisible by i. If all the above conditions are satisfied until all the digits are exhausted,then the given number is Polydivisible. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // CPP program to check whether// a number is polydivisible or not#include <bits/stdc++.h>using namespace std; // function to check polydivisible// numbervoid check_polydivisible(int n){ int N = n; vector<int> digit; // digit extraction of input number while (n > 0) { // store the digits in an array digit.push_back(n % 10); n /= 10; } reverse(digit.begin(), digit.end()); bool flag = true; n = digit[0]; for (int i = 1; i < digit.size(); i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) cout << N << " is Polydivisible number."; else cout << N << " is Not Polydivisible number.";} int main(){ int n = 345654; check_polydivisible(n);} // Java program to check whether// a number is polydivisible or notimport java.util.*;import java.io.*; class GFG { // function to check polydivisible // number static void check_polydivisible(int n) { int N = n; Vector<Integer> digit = new Vector<Integer>(); // digit extraction of input number while (n > 0) { // store the digits in an array digit.add(new Integer(n % 10)); n /= 10; } Collections.reverse(digit); boolean flag = true; n = digit.get(0); for (int i = 1; i < digit.size(); i++) { // n contains first i digits n = n * 10 + digit.get(i); // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) System.out.println(N + " is Polydivisible number."); else System.out.println(N + " is Not Polydivisible number."); } // Driver code public static void main (String[] args) { int n = 345654; check_polydivisible(n); }} # Python 3 program to check whether# a number is polydivisible or not # function to check polydivisible# numberdef check_polydivisible(n): N = n digit = [] # digit extraction of input number while (n > 0): # store the digits in an array digit.append(n % 10) n //= 10 digit = digit[::-1] flag = True n = digit[0] for i in range(1, len(digit), 1): # n contains first i digits n = n * 10 + digit[i] # n should be divisible by i if (n % (i + 1) != 0): flag = False break if (flag): print(N, "is Polydivisible number.") else: print(N, "is Not Polydivisible number.") # Driver Codeif __name__ == '__main__': n = 345654 check_polydivisible(n) # This code is contributed by# Sahil_Shelangia# Improved by Madhushree Sannigrahi // C# program to check whether// a number is polydivisible or notusing System;using System.Collections.Generic; class GFG{ // function to check polydivisible // number static void check_polydivisible(int n) { int N = n; List<int> digit = new List<int>(); // digit extraction of input number while (n > 0) { // store the digits in an array digit.Add((int)n % 10); n /= 10; } digit.Reverse(); bool flag = true; n = digit[0]; for (int i = 1; i < digit.Count; i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) Console.WriteLine(N + " is Polydivisible number."); else Console.WriteLine(N + " is Not Polydivisible number."); } // Driver code public static void Main (String[] args) { int n = 345654; check_polydivisible(n); }} // This code is contributed by Rajput-Ji <script> // Javascript program to check whether // a number is polydivisible or not // function to check polydivisible // number function check_polydivisible(n) { let N = n; let digit = []; // digit extraction of input number while (n > 0) { // store the digits in an array digit.push(n % 10); n = parseInt(n / 10, 10); } digit.reverse(); let flag = true; n = digit[0]; for (let i = 1; i < digit.length; i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) document.write(N + " is Polydivisible number." + "</br>"); else document.write(N + " is Not Polydivisible number."); } let n = 345654; check_polydivisible(n); </script> 345654 is Polydivisible number. sahilshelangia Rajput-Ji rameshtravel07 madhushree162000 divisibility number-digits number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Find first and last digits of a number Count ways to reach the n'th stair Program to convert a given number to words Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24716, "s": 24688, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25092, "s": 24716, "text": "Given an integer n, find whether n is a Polydivisible or not. In mathematics, a number is called Polydivisible if it follows some unique properties. The number should not have any leading zeroes. The number formed by first i digits of the input number should be divisible by i, where . If any number follow these properties then it is called Polydivisible number. Examples: " }, { "code": null, "e": 25643, "s": 25092, "text": "Input: 345654\nOutput: 345654 is Polydivisible number.\nExplanation: \nThe first digit of the number is non-zero. \nThe number formed by the first 2 digits(34) \nis divisible by 2. The number formed by the\nfirst 3 digits(345) is divisible by 3. \nThe number formed by the first 4 digits(3456)\nis divisible by 4. The number formed by the\nfirst 5 digits(34565) is divisible by 5. \nThe number formed by the first 6 digits(345654)\nis divisible by 6. \n\nInput: 130\nOutput: 130 is Not Polydivisible number.\n\nInput: 129\nOutput: 129 is Polydivisible number. " }, { "code": null, "e": 25682, "s": 25645, "text": "Approach: The idea is very simple. " }, { "code": null, "e": 26025, "s": 25682, "text": "Extract all the digits of the array and store them in an array.Pick first 2 digits and form a number and check if it is divisible by 2.Pick ith digit and append to the existing number and check if the number is divisible by i.If all the above conditions are satisfied until all the digits are exhausted,then the given number is Polydivisible." }, { "code": null, "e": 26089, "s": 26025, "text": "Extract all the digits of the array and store them in an array." }, { "code": null, "e": 26162, "s": 26089, "text": "Pick first 2 digits and form a number and check if it is divisible by 2." }, { "code": null, "e": 26254, "s": 26162, "text": "Pick ith digit and append to the existing number and check if the number is divisible by i." }, { "code": null, "e": 26371, "s": 26254, "text": "If all the above conditions are satisfied until all the digits are exhausted,then the given number is Polydivisible." }, { "code": null, "e": 26423, "s": 26371, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 26427, "s": 26423, "text": "C++" }, { "code": null, "e": 26432, "s": 26427, "text": "Java" }, { "code": null, "e": 26440, "s": 26432, "text": "Python3" }, { "code": null, "e": 26443, "s": 26440, "text": "C#" }, { "code": null, "e": 26454, "s": 26443, "text": "Javascript" }, { "code": "// CPP program to check whether// a number is polydivisible or not#include <bits/stdc++.h>using namespace std; // function to check polydivisible// numbervoid check_polydivisible(int n){ int N = n; vector<int> digit; // digit extraction of input number while (n > 0) { // store the digits in an array digit.push_back(n % 10); n /= 10; } reverse(digit.begin(), digit.end()); bool flag = true; n = digit[0]; for (int i = 1; i < digit.size(); i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) cout << N << \" is Polydivisible number.\"; else cout << N << \" is Not Polydivisible number.\";} int main(){ int n = 345654; check_polydivisible(n);}", "e": 27328, "s": 26454, "text": null }, { "code": "// Java program to check whether// a number is polydivisible or notimport java.util.*;import java.io.*; class GFG { // function to check polydivisible // number static void check_polydivisible(int n) { int N = n; Vector<Integer> digit = new Vector<Integer>(); // digit extraction of input number while (n > 0) { // store the digits in an array digit.add(new Integer(n % 10)); n /= 10; } Collections.reverse(digit); boolean flag = true; n = digit.get(0); for (int i = 1; i < digit.size(); i++) { // n contains first i digits n = n * 10 + digit.get(i); // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) System.out.println(N + \" is Polydivisible number.\"); else System.out.println(N + \" is Not Polydivisible number.\"); } // Driver code public static void main (String[] args) { int n = 345654; check_polydivisible(n); }}", "e": 28485, "s": 27328, "text": null }, { "code": "# Python 3 program to check whether# a number is polydivisible or not # function to check polydivisible# numberdef check_polydivisible(n): N = n digit = [] # digit extraction of input number while (n > 0): # store the digits in an array digit.append(n % 10) n //= 10 digit = digit[::-1] flag = True n = digit[0] for i in range(1, len(digit), 1): # n contains first i digits n = n * 10 + digit[i] # n should be divisible by i if (n % (i + 1) != 0): flag = False break if (flag): print(N, \"is Polydivisible number.\") else: print(N, \"is Not Polydivisible number.\") # Driver Codeif __name__ == '__main__': n = 345654 check_polydivisible(n) # This code is contributed by# Sahil_Shelangia# Improved by Madhushree Sannigrahi", "e": 29363, "s": 28485, "text": null }, { "code": "// C# program to check whether// a number is polydivisible or notusing System;using System.Collections.Generic; class GFG{ // function to check polydivisible // number static void check_polydivisible(int n) { int N = n; List<int> digit = new List<int>(); // digit extraction of input number while (n > 0) { // store the digits in an array digit.Add((int)n % 10); n /= 10; } digit.Reverse(); bool flag = true; n = digit[0]; for (int i = 1; i < digit.Count; i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) Console.WriteLine(N + \" is Polydivisible number.\"); else Console.WriteLine(N + \" is Not Polydivisible number.\"); } // Driver code public static void Main (String[] args) { int n = 345654; check_polydivisible(n); }} // This code is contributed by Rajput-Ji", "e": 30586, "s": 29363, "text": null }, { "code": "<script> // Javascript program to check whether // a number is polydivisible or not // function to check polydivisible // number function check_polydivisible(n) { let N = n; let digit = []; // digit extraction of input number while (n > 0) { // store the digits in an array digit.push(n % 10); n = parseInt(n / 10, 10); } digit.reverse(); let flag = true; n = digit[0]; for (let i = 1; i < digit.length; i++) { // n contains first i digits n = n * 10 + digit[i]; // n should be divisible by i if (n % (i + 1) != 0) { flag = false; break; } } if (flag) document.write(N + \" is Polydivisible number.\" + \"</br>\"); else document.write(N + \" is Not Polydivisible number.\"); } let n = 345654; check_polydivisible(n); </script>", "e": 31634, "s": 30586, "text": null }, { "code": null, "e": 31666, "s": 31634, "text": "345654 is Polydivisible number." }, { "code": null, "e": 31683, "s": 31668, "text": "sahilshelangia" }, { "code": null, "e": 31693, "s": 31683, "text": "Rajput-Ji" }, { "code": null, "e": 31708, "s": 31693, "text": "rameshtravel07" }, { "code": null, "e": 31725, "s": 31708, "text": "madhushree162000" }, { "code": null, "e": 31738, "s": 31725, "text": "divisibility" }, { "code": null, "e": 31752, "s": 31738, "text": "number-digits" }, { "code": null, "e": 31766, "s": 31752, "text": "number-theory" }, { "code": null, "e": 31779, "s": 31766, "text": "Mathematical" }, { "code": null, "e": 31793, "s": 31779, "text": "number-theory" }, { "code": null, "e": 31806, "s": 31793, "text": "Mathematical" }, { "code": null, "e": 31904, "s": 31806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31936, "s": 31904, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 31980, "s": 31936, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32005, "s": 31980, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32038, "s": 32005, "text": "Program to multiply two matrices" }, { "code": null, "e": 32069, "s": 32038, "text": "Modular multiplicative inverse" }, { "code": null, "e": 32101, "s": 32069, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32140, "s": 32101, "text": "Find first and last digits of a number" }, { "code": null, "e": 32175, "s": 32140, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 32218, "s": 32175, "text": "Program to convert a given number to words" } ]
Functional programming for deep learning | by Joyce Xu | Towards Data Science
Before I started my most recent job at ThinkTopic, the concepts of “functional programming” and “machine learning” belonged to two different worlds entirely. One was a programming paradigm surging in popularity as the world turned towards simplicity, composability, and immutability to maintain complex scaling applications; the other was a tool to teach computers to autocomplete doodles and make music. Where was the overlap? The more I worked with the two, the more I began realizing that the overlap is both practical and theoretical. Firstly, machine learning is not a stand-alone endeavor; it needs to be rapidly incorporated into complex scaling applications in industry. Secondly, machine learning — and deep learning in particular — is functional by design. Given the right ecosystem, there are several compelling reasons to perform deep learning in an entirely functional manner: Deep learning models are compositional. Functional programming is all about composing chains of higher-order functions to operate over simple data structures. Neural nets are designed the same way, chaining together function transformations from one layer to the next to operate over a simple matrix of input data. In fact, the entire process of deep learning can be viewed as optimizing a set of composed functions, meaning the models themselves are intrinsically functional. Deep learning components are immutable. When functions operate over the input data, the data is not changed, a new set of values are outputted and passed on. Furthermore, when weights are updated, they do not need to be “mutated” — they can just be replaced by a new value. In theory, the updates to the weights can be applied in any order (i.e. they are not dependent on one another), so there is no need to keep track of a sequential, mutable state. Functional programming offers easy parallelism. Most importantly, functions that are pure and composable are easy to parallelize. Parallelism means more speed and more compute power. Functional programming gives us concurrency and parallelism at essentially no cost, making it much easier to work with large, distributed models in deep learning. There are many theories and perspectives regarding the combination of functional programming and deep learning, from mathematical arguments to practical overviews, but sometimes it’s most convincing (and useful) just to see it in practice. Here at ThinkTopic, we’ve been developing an open-source machine learning library called Cortex. For the rest of this post, I will introduce some ideas behind functional programming and put them to use in a Cortex deep learning model for anomaly detection. Before we continue on our Cortex tutorial, I want to introduce some basics of Clojure. Clojure is a functional programming language that’s really good at two things: concurrency and data processing. Fortunately for us, both of those things are incredibly useful for machine learning. In fact, one of the primary reasons we use Clojure for machine learning is the fact that day-to-day work in preparing datasets for training (data manipulation, processing, etc.) can easily outweigh the work of implementing the algorithms, especially when we have a solid library such as Cortex for learning. Using Clojure and .edn (instead of C++ and protobuf), we can gain leverage and velocity on ML projects. For a more in-depth introduction to the language, take a look at the community guide here. On with the basics: Clojure code is made up of a bunch of expressions that are evaluated at run-time. These expressions are wrapped in parentheses, and are typically treated as function calls. (+ 2 3) ; => 5(if false 1 0) ; => 0 There are 4 basic collection data structures: vectors, lists, hash-maps, and sets. Commas are treated as whitespace, so they are typically omitted. [1 2 3] ; vector (ordered)'(1 2 3) ; list (ordered){:a 1 :b 2 :c 3} ; hashmap or map (unordered)#{1 2 3} ; set (unordered, unique values) The single quote in front of the list simply prevents it from being evaluated as an expression. Clojure also comes with many, many, built-in functions to operate over these data structures. Part of the beauty of Clojure is that it was designed to have many functions for very few data types, as opposed to to having a few specialized functions for each of many data types. Being an FP language, Clojure supports higher-order functions, meaning functions can be passed around as arguments to other functions. (count [a b c]) ; => 3(range 5) ; => (0 1 2 3 4)(take 2 (drop 5 (range 10))) ; => (5 6)(:b {:a 1 :b 2 :c 3}) ; use keyword as function => 2(map inc [1 2 3]) ; map and increment => (2 3 4)(filter even? (range 5)) ; filter collection based off predicate => (0 2 4)(reduce + [1 2 3 4]) ; apply + to first two elements, then apply + to that result and the 3rd element, and so forth => 10 Of course, we can also write our own functions in Clojure, using defn. Clojure function definitions follow the form (defn fn-name [params*] expressions), and they always return the value of the last expression in the body. (defn add2 [x] (+ x 2))(add2 5) ; => 7 let expressions create and bind variables within the lexical scope of the “let”. That is, in of the expression (let [a 4] (...)), the variable “a” takes on a value of 4 inside (and only inside) the inner parentheses. These variables are called “locals.” (defn square-and-add [a b] (let [a-squared (* a a) b-squared (* b b)] (+ a-squared b-squared)))(square-and-add 3 4) ; => 25 Finally, there are a couple of ways to create anonymous functions, which can either be assigned to a local or passed to a higher-order function. (fn [x] (* 5 x)) ; anonymous function#(* 5 %) ; equivalent anonymous function, where the % represents the function's argument(map #(* 5 %) [1 2 3]) ; => (5 10 15) That’s it for the basics! Now that we’ve learned some Clojure, let’s put the fun in functional programming and get back to some ML. Cortex is written in Clojure, and is currently one of the largest and fastest-growing machine learning libraries that uses a functional programming language. The rest of this post will walk through how to build a state-of-the-art classification model in Cortex, and the functional programming paradigms and data augmentation techniques required to do so. Our dataset is going to be the credit card fraud detection data provided by Kaggle here. It turns out this dataset is incredibly imbalanced, containing only 492 positive fraud cases out of 284,807. That’s 0.172%. This is going to cause problems for us later, but first let’s just take a look at the data and see how the model does. In order to ensure anonymity of personal data, all the original features except “time” and “amount” have already been transformed to PCA components (where each entry represents a new variable that contains the most relevant information from the raw data). A little data exploration will show that the first “time” variable is fairly uninformative, so we’ll drop that as we’re reading in the data. Here is what our initial code looks like: Cortex neural nets expect input data in the form of maps, such that each map represents a single labeled data point. For example, a classification dataset could look like [{:data [12 10 38] :label “cat”} {:data [20 39 3] :label “dog“} ... ]. In our create-dataset function, we read in the csv data file, designate all but the last column to be the “data” (or features), and designate the last column to be the labels. In the process, we turn the labels into one-hot vectors (e.g. [0 1 0 0]) based on the classification class, because the last softmax layer of our neural net returns a vector of class probabilities, not the actual label. Finally, we create a map from these two variables and return it as the dataset. Creating a model in Cortex is fairly straightforward. First, we’re going to define a map of hyper-parameters to be used later during training. Then, to define a model, we simply string the layers together: network-description is a vector of neural network layers. Our model consists of: an input layer a fully-connected (linear) layer with the ReLU activation function a dropout layer another fully-connected ReLU layer an output layer of size 2 that is passed through the softmax function. In both the first and the last layers, we need to specify an :id. This id refers to the key in the data map that our network should look at. (Recall that the data map looks like {:data [...] :label [...]}). For our input layer, we pass in the :data id to tell the model to grab the training data for its forward passes. In our final network layer, we provide :label as the :id, so the model can use the true label to calculate our error with. Here’s where it gets a little more difficult. The train function itself is actually not so complicated — Cortex provides a nice, high-level call for training, so all we have to do is pass in our parameters (the network, training and testing dataset, etc.). The only caveat is that that the system expects an effectively “infinite” dataset for training, but Cortex provides a function (infinite-class-balanced-dataset) to help us transform it. The complicated part is the f1-test-fn. Here’s the thing: during training, the train-n function expects to be provided with a :test-fn that evaluates how well the model is performing and determines whether or not it should be saved as the “best network.” There is a default test function that evaluates cross-entropy loss, but this loss value is not so easy to interpret, and it doesn’t suit our imbalanced dataset very well. To get around this problem, we’re going to write our own test function. But how are we going to test the performance of the model? The standard metric in classification tasks is accuracy, but in a dataset as imbalanced as ours, accuracy is a fairly useless metric. Because positive (fraudulent) examples account for just 0.172% of our dataset, even a model that exclusively predicts negative examples would achieve 99.828% accuracy. 99.828% is a pretty darn good accuracy, but if Amazon really used this model, we may as well all turn to a life of crime and credit card fraud. Thankfully, Amazon does not use this kind of model, and neither shall we. A much more telling set of metrics is precision, recall, and the F1 (or more generally F-beta) score. In layman’s terms, precision asks the question: “of all the examples I guessed were positive, what proportion were actually positive?” and recall asks the question: “of all the examples that were actually positive, what proportion did I correctly guess as positive?” The F-beta score (a generalization of the traditional F1 score) is a weighted average of precision and recall, also measured on a scale of 0 to 1: When beta = 1, we get the standard F1 measure of 2 * (precision * recall) / (precision + recall). In general, beta represents how many times more important recall should be than precision. For our fraud detection model, we’ll use the F1 score as our high score to track, but we’ll log the precision and recall scores as well to check the balance. This is our f1-test-fn: The function runs the current network on the test set, calculates the F1 score, and updates/saves the network accordingly. It also prints out our evaluation metrics at each epoch. If we run (train) in the REPL now, we get a high score that something that looks like this: Epoch: 30Precision: 0.2515923566878981Recall: 0.9186046511627907F1: 0.395 Haha. That’s pretty embarrassingly bad. Here’s the problem. Remember how I said our highly imbalanced dataset was going to cause issues for us later? The model currently does not have enough positive examples to learn from. When we call experiment-util/infinite-class-balanced-dataset in our train function, we’re actually creating hundreds of copies of each positive training instance to balance out the dataset. As a result, the model is effectively memorizing those feature values and not actually learning the distinction between the classes. One way around this problem is through data augmentation, in which we generate additional, artificial data based on the examples we already have. In order to create realistic positive training examples, we are going to add random amounts of noise to the feature vectors of each of our existing positive examples. The amount of noise we add will be dependent on the variance of each feature across the positive class, such that features with a large variance will be augmented with a large amount of noise, and vice versa for features with small variances. Here is our code for data augmentation: augment-train-ds takes our original train dataset, calculates the number of augmentations that have to be made to reach a 50/50 class balance, and applies those augmentations to our existing samples by adding a random noise vector (add-rand-variance) based on the allowed variance (get-scaled-variances). In the end, we concatenate the augmented examples back in to the original dataset and return the balanced dataset. During training, the model will be seeing an unrealistically large amount of positive examples, while the test set will still be only 0.172% positives. As a result, while the model may be able to learn the differences between the two classes better, it will over-predict positive examples during testing. In order to fix this, we can require a higher threshold of certainty to predict “positive” during testing. In other words, instead of requiring the model to be at least 50% certain that an example is positive in order to classify it as such, we can require it to be at least 70% certain. After some testing, I found the optimal value to be set at 90%. The code for this can be found in the vec->label function in the source code, and is called on line 31 of the f1-test-fn. Using the new, augmented dataset for training, our high scores look something like this: Epoch: 25Precision: 0.8658536585365854Recall: 0.8255813953488372F1: 0.8452380952380953 Much better! As always, the model can still be improved. Here are a few ideas for next steps: Are all the PCA features informative? Take a look at the distribution of values for positive and negative examples across the features, and drop any features that do not help distinguish between the two classes. Are there other neural net architectures, activation functions, etc. that perform better? Are there different data augmentation techniques that would perform better? How does model performance in Cortex compare to Keras/Tensorflow/Theano/Caffe? The source code for the project can be found in its entirety here. I encourage you to try some of these next steps, test out new datasets, and explore different network architectures (we have a great image classification example for reference on conv nets). Cortex is pushing towards its 1.0 release, so if you have any thoughts, recommendations, or feedback, be sure to let us know. Happy hacking!
[ { "code": null, "e": 600, "s": 172, "text": "Before I started my most recent job at ThinkTopic, the concepts of “functional programming” and “machine learning” belonged to two different worlds entirely. One was a programming paradigm surging in popularity as the world turned towards simplicity, composability, and immutability to maintain complex scaling applications; the other was a tool to teach computers to autocomplete doodles and make music. Where was the overlap?" }, { "code": null, "e": 1062, "s": 600, "text": "The more I worked with the two, the more I began realizing that the overlap is both practical and theoretical. Firstly, machine learning is not a stand-alone endeavor; it needs to be rapidly incorporated into complex scaling applications in industry. Secondly, machine learning — and deep learning in particular — is functional by design. Given the right ecosystem, there are several compelling reasons to perform deep learning in an entirely functional manner:" }, { "code": null, "e": 1539, "s": 1062, "text": "Deep learning models are compositional. Functional programming is all about composing chains of higher-order functions to operate over simple data structures. Neural nets are designed the same way, chaining together function transformations from one layer to the next to operate over a simple matrix of input data. In fact, the entire process of deep learning can be viewed as optimizing a set of composed functions, meaning the models themselves are intrinsically functional." }, { "code": null, "e": 1991, "s": 1539, "text": "Deep learning components are immutable. When functions operate over the input data, the data is not changed, a new set of values are outputted and passed on. Furthermore, when weights are updated, they do not need to be “mutated” — they can just be replaced by a new value. In theory, the updates to the weights can be applied in any order (i.e. they are not dependent on one another), so there is no need to keep track of a sequential, mutable state." }, { "code": null, "e": 2337, "s": 1991, "text": "Functional programming offers easy parallelism. Most importantly, functions that are pure and composable are easy to parallelize. Parallelism means more speed and more compute power. Functional programming gives us concurrency and parallelism at essentially no cost, making it much easier to work with large, distributed models in deep learning." }, { "code": null, "e": 2834, "s": 2337, "text": "There are many theories and perspectives regarding the combination of functional programming and deep learning, from mathematical arguments to practical overviews, but sometimes it’s most convincing (and useful) just to see it in practice. Here at ThinkTopic, we’ve been developing an open-source machine learning library called Cortex. For the rest of this post, I will introduce some ideas behind functional programming and put them to use in a Cortex deep learning model for anomaly detection." }, { "code": null, "e": 3530, "s": 2834, "text": "Before we continue on our Cortex tutorial, I want to introduce some basics of Clojure. Clojure is a functional programming language that’s really good at two things: concurrency and data processing. Fortunately for us, both of those things are incredibly useful for machine learning. In fact, one of the primary reasons we use Clojure for machine learning is the fact that day-to-day work in preparing datasets for training (data manipulation, processing, etc.) can easily outweigh the work of implementing the algorithms, especially when we have a solid library such as Cortex for learning. Using Clojure and .edn (instead of C++ and protobuf), we can gain leverage and velocity on ML projects." }, { "code": null, "e": 3621, "s": 3530, "text": "For a more in-depth introduction to the language, take a look at the community guide here." }, { "code": null, "e": 3814, "s": 3621, "text": "On with the basics: Clojure code is made up of a bunch of expressions that are evaluated at run-time. These expressions are wrapped in parentheses, and are typically treated as function calls." }, { "code": null, "e": 3861, "s": 3814, "text": "(+ 2 3) ; => 5(if false 1 0) ; => 0" }, { "code": null, "e": 4009, "s": 3861, "text": "There are 4 basic collection data structures: vectors, lists, hash-maps, and sets. Commas are treated as whitespace, so they are typically omitted." }, { "code": null, "e": 4180, "s": 4009, "text": "[1 2 3] ; vector (ordered)'(1 2 3) ; list (ordered){:a 1 :b 2 :c 3} ; hashmap or map (unordered)#{1 2 3} ; set (unordered, unique values)" }, { "code": null, "e": 4276, "s": 4180, "text": "The single quote in front of the list simply prevents it from being evaluated as an expression." }, { "code": null, "e": 4688, "s": 4276, "text": "Clojure also comes with many, many, built-in functions to operate over these data structures. Part of the beauty of Clojure is that it was designed to have many functions for very few data types, as opposed to to having a few specialized functions for each of many data types. Being an FP language, Clojure supports higher-order functions, meaning functions can be passed around as arguments to other functions." }, { "code": null, "e": 5134, "s": 4688, "text": "(count [a b c]) ; => 3(range 5) ; => (0 1 2 3 4)(take 2 (drop 5 (range 10))) ; => (5 6)(:b {:a 1 :b 2 :c 3}) ; use keyword as function => 2(map inc [1 2 3]) ; map and increment => (2 3 4)(filter even? (range 5)) ; filter collection based off predicate => (0 2 4)(reduce + [1 2 3 4]) ; apply + to first two elements, then apply + to that result and the 3rd element, and so forth => 10" }, { "code": null, "e": 5357, "s": 5134, "text": "Of course, we can also write our own functions in Clojure, using defn. Clojure function definitions follow the form (defn fn-name [params*] expressions), and they always return the value of the last expression in the body." }, { "code": null, "e": 5402, "s": 5357, "text": "(defn add2 [x] (+ x 2))(add2 5) ; => 7" }, { "code": null, "e": 5656, "s": 5402, "text": "let expressions create and bind variables within the lexical scope of the “let”. That is, in of the expression (let [a 4] (...)), the variable “a” takes on a value of 4 inside (and only inside) the inner parentheses. These variables are called “locals.”" }, { "code": null, "e": 5798, "s": 5656, "text": "(defn square-and-add [a b] (let [a-squared (* a a) b-squared (* b b)] (+ a-squared b-squared)))(square-and-add 3 4) ; => 25" }, { "code": null, "e": 5943, "s": 5798, "text": "Finally, there are a couple of ways to create anonymous functions, which can either be assigned to a local or passed to a higher-order function." }, { "code": null, "e": 6135, "s": 5943, "text": "(fn [x] (* 5 x)) ; anonymous function#(* 5 %) ; equivalent anonymous function, where the % represents the function's argument(map #(* 5 %) [1 2 3]) ; => (5 10 15)" }, { "code": null, "e": 6267, "s": 6135, "text": "That’s it for the basics! Now that we’ve learned some Clojure, let’s put the fun in functional programming and get back to some ML." }, { "code": null, "e": 6622, "s": 6267, "text": "Cortex is written in Clojure, and is currently one of the largest and fastest-growing machine learning libraries that uses a functional programming language. The rest of this post will walk through how to build a state-of-the-art classification model in Cortex, and the functional programming paradigms and data augmentation techniques required to do so." }, { "code": null, "e": 6954, "s": 6622, "text": "Our dataset is going to be the credit card fraud detection data provided by Kaggle here. It turns out this dataset is incredibly imbalanced, containing only 492 positive fraud cases out of 284,807. That’s 0.172%. This is going to cause problems for us later, but first let’s just take a look at the data and see how the model does." }, { "code": null, "e": 7393, "s": 6954, "text": "In order to ensure anonymity of personal data, all the original features except “time” and “amount” have already been transformed to PCA components (where each entry represents a new variable that contains the most relevant information from the raw data). A little data exploration will show that the first “time” variable is fairly uninformative, so we’ll drop that as we’re reading in the data. Here is what our initial code looks like:" }, { "code": null, "e": 8111, "s": 7393, "text": "Cortex neural nets expect input data in the form of maps, such that each map represents a single labeled data point. For example, a classification dataset could look like [{:data [12 10 38] :label “cat”} {:data [20 39 3] :label “dog“} ... ]. In our create-dataset function, we read in the csv data file, designate all but the last column to be the “data” (or features), and designate the last column to be the labels. In the process, we turn the labels into one-hot vectors (e.g. [0 1 0 0]) based on the classification class, because the last softmax layer of our neural net returns a vector of class probabilities, not the actual label. Finally, we create a map from these two variables and return it as the dataset." }, { "code": null, "e": 8317, "s": 8111, "text": "Creating a model in Cortex is fairly straightforward. First, we’re going to define a map of hyper-parameters to be used later during training. Then, to define a model, we simply string the layers together:" }, { "code": null, "e": 8398, "s": 8317, "text": "network-description is a vector of neural network layers. Our model consists of:" }, { "code": null, "e": 8413, "s": 8398, "text": "an input layer" }, { "code": null, "e": 8480, "s": 8413, "text": "a fully-connected (linear) layer with the ReLU activation function" }, { "code": null, "e": 8496, "s": 8480, "text": "a dropout layer" }, { "code": null, "e": 8531, "s": 8496, "text": "another fully-connected ReLU layer" }, { "code": null, "e": 8602, "s": 8531, "text": "an output layer of size 2 that is passed through the softmax function." }, { "code": null, "e": 9045, "s": 8602, "text": "In both the first and the last layers, we need to specify an :id. This id refers to the key in the data map that our network should look at. (Recall that the data map looks like {:data [...] :label [...]}). For our input layer, we pass in the :data id to tell the model to grab the training data for its forward passes. In our final network layer, we provide :label as the :id, so the model can use the true label to calculate our error with." }, { "code": null, "e": 9488, "s": 9045, "text": "Here’s where it gets a little more difficult. The train function itself is actually not so complicated — Cortex provides a nice, high-level call for training, so all we have to do is pass in our parameters (the network, training and testing dataset, etc.). The only caveat is that that the system expects an effectively “infinite” dataset for training, but Cortex provides a function (infinite-class-balanced-dataset) to help us transform it." }, { "code": null, "e": 9986, "s": 9488, "text": "The complicated part is the f1-test-fn. Here’s the thing: during training, the train-n function expects to be provided with a :test-fn that evaluates how well the model is performing and determines whether or not it should be saved as the “best network.” There is a default test function that evaluates cross-entropy loss, but this loss value is not so easy to interpret, and it doesn’t suit our imbalanced dataset very well. To get around this problem, we’re going to write our own test function." }, { "code": null, "e": 10491, "s": 9986, "text": "But how are we going to test the performance of the model? The standard metric in classification tasks is accuracy, but in a dataset as imbalanced as ours, accuracy is a fairly useless metric. Because positive (fraudulent) examples account for just 0.172% of our dataset, even a model that exclusively predicts negative examples would achieve 99.828% accuracy. 99.828% is a pretty darn good accuracy, but if Amazon really used this model, we may as well all turn to a life of crime and credit card fraud." }, { "code": null, "e": 10667, "s": 10491, "text": "Thankfully, Amazon does not use this kind of model, and neither shall we. A much more telling set of metrics is precision, recall, and the F1 (or more generally F-beta) score." }, { "code": null, "e": 10934, "s": 10667, "text": "In layman’s terms, precision asks the question: “of all the examples I guessed were positive, what proportion were actually positive?” and recall asks the question: “of all the examples that were actually positive, what proportion did I correctly guess as positive?”" }, { "code": null, "e": 11081, "s": 10934, "text": "The F-beta score (a generalization of the traditional F1 score) is a weighted average of precision and recall, also measured on a scale of 0 to 1:" }, { "code": null, "e": 11452, "s": 11081, "text": "When beta = 1, we get the standard F1 measure of 2 * (precision * recall) / (precision + recall). In general, beta represents how many times more important recall should be than precision. For our fraud detection model, we’ll use the F1 score as our high score to track, but we’ll log the precision and recall scores as well to check the balance. This is our f1-test-fn:" }, { "code": null, "e": 11724, "s": 11452, "text": "The function runs the current network on the test set, calculates the F1 score, and updates/saves the network accordingly. It also prints out our evaluation metrics at each epoch. If we run (train) in the REPL now, we get a high score that something that looks like this:" }, { "code": null, "e": 11798, "s": 11724, "text": "Epoch: 30Precision: 0.2515923566878981Recall: 0.9186046511627907F1: 0.395" }, { "code": null, "e": 11838, "s": 11798, "text": "Haha. That’s pretty embarrassingly bad." }, { "code": null, "e": 12345, "s": 11838, "text": "Here’s the problem. Remember how I said our highly imbalanced dataset was going to cause issues for us later? The model currently does not have enough positive examples to learn from. When we call experiment-util/infinite-class-balanced-dataset in our train function, we’re actually creating hundreds of copies of each positive training instance to balance out the dataset. As a result, the model is effectively memorizing those feature values and not actually learning the distinction between the classes." }, { "code": null, "e": 12901, "s": 12345, "text": "One way around this problem is through data augmentation, in which we generate additional, artificial data based on the examples we already have. In order to create realistic positive training examples, we are going to add random amounts of noise to the feature vectors of each of our existing positive examples. The amount of noise we add will be dependent on the variance of each feature across the positive class, such that features with a large variance will be augmented with a large amount of noise, and vice versa for features with small variances." }, { "code": null, "e": 12941, "s": 12901, "text": "Here is our code for data augmentation:" }, { "code": null, "e": 13361, "s": 12941, "text": "augment-train-ds takes our original train dataset, calculates the number of augmentations that have to be made to reach a 50/50 class balance, and applies those augmentations to our existing samples by adding a random noise vector (add-rand-variance) based on the allowed variance (get-scaled-variances). In the end, we concatenate the augmented examples back in to the original dataset and return the balanced dataset." }, { "code": null, "e": 14140, "s": 13361, "text": "During training, the model will be seeing an unrealistically large amount of positive examples, while the test set will still be only 0.172% positives. As a result, while the model may be able to learn the differences between the two classes better, it will over-predict positive examples during testing. In order to fix this, we can require a higher threshold of certainty to predict “positive” during testing. In other words, instead of requiring the model to be at least 50% certain that an example is positive in order to classify it as such, we can require it to be at least 70% certain. After some testing, I found the optimal value to be set at 90%. The code for this can be found in the vec->label function in the source code, and is called on line 31 of the f1-test-fn." }, { "code": null, "e": 14229, "s": 14140, "text": "Using the new, augmented dataset for training, our high scores look something like this:" }, { "code": null, "e": 14316, "s": 14229, "text": "Epoch: 25Precision: 0.8658536585365854Recall: 0.8255813953488372F1: 0.8452380952380953" }, { "code": null, "e": 14329, "s": 14316, "text": "Much better!" }, { "code": null, "e": 14410, "s": 14329, "text": "As always, the model can still be improved. Here are a few ideas for next steps:" }, { "code": null, "e": 14622, "s": 14410, "text": "Are all the PCA features informative? Take a look at the distribution of values for positive and negative examples across the features, and drop any features that do not help distinguish between the two classes." }, { "code": null, "e": 14712, "s": 14622, "text": "Are there other neural net architectures, activation functions, etc. that perform better?" }, { "code": null, "e": 14788, "s": 14712, "text": "Are there different data augmentation techniques that would perform better?" }, { "code": null, "e": 14867, "s": 14788, "text": "How does model performance in Cortex compare to Keras/Tensorflow/Theano/Caffe?" } ]
Create an Image Classification Web App using PyTorch and Streamlit | by Dehao Zhang | Towards Data Science
You just developed a cool ML model. You are proud of it. You want to show it to your friends through a web demo so they can interact with your model and provide feedback. However, you are not familiar with common frameworks such as Django and Flask. You start to ask yourself: Is there a way to build a quick web demo with minimal framework? What is Streamlit?How to make the UI?How to create the image classification model?What does the result look like?What can we do next? What is Streamlit? How to make the UI? How to create the image classification model? What does the result look like? What can we do next? In this post, I will walk through a quick example of how you can use Streamlit to build a simple web app. Streamlit is an open-source Python library that makes it easy to build custom web apps for machine learning and data science [1]. Check out its gallery here to see some applications that other people have created. I have chosen image classification here as an example because computer vision (CV) is one of the most popular areas of AI currently, powered by deep learning algorithms. It also has a wide range of applications, such as classifying medical images to help doctors in disease diagnosis [2]. Learn more about image classification with deep learning models here. For demonstration purposes, I will use a pretrained ResNet model from PyTorch, and for the same task, you can always use other libraries (TensorFlow, Keras, etc.), other architecture, or even customize your own model. To see my full Python code, check out my Github page. Now without further ado, let’s get started! The first step is to install the Streamlit library, and you can do that using the pip command. I recommend that you use a Python virtual environment to keep your dependencies separately for each project. $ pip install streamlit After it is installed successfully, you can do a quick check with a simple ‘Hello World’ app: $ streamlit hello For our application, one key element is to enable users to upload images for the model to make predictions, and this can be done with the ‘file_uploader’ function: import streamlit as stfile_up = st.file_uploader("Upload an image", type="jpg") Make sure to specify the appropriate file type so it works properly with the classification model. Then we can display this image: from PIL import Imageimage = Image.open(file_up)st.image(image, caption='Uploaded Image.', use_column_width=True) Apart from that, we will also use ‘set_title’ to create a title for the app and ‘write’ to display prediction results. To use a pretrained model from PyTorch, make sure you have installed both ‘torch’ and ‘torchvision’ library. Now we can create a ResNet model: from torchvision import models, transformsimport torchresnet = models.resnet101(pretrained=True) To put it in simple terms, Residual Network (ResNet) is an improved Convolutional Neuron Network (CNN), trained in the well-known ImageNet database, and it has achieved great performance in CV tasks such as image classification and object detection. This particular model ‘resnet101’ means it has 101 layers (Deep!). Read more about ResNet and its variant here. After we create this model, we need to transform the input image through resizing, normalization, etc. Here we make use of the ‘transforms’ module in ‘torchvision’: transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] )]) Note that the images are normalized according to its mean and standard deviation. See the documentation for details. Now we are able to load the image, pre-process it, and make predictions: img = Image.open(image_path)batch_t = torch.unsqueeze(transform(img), 0)resnet.eval()out = resnet(batch_t) Next, we can return the top 5 predictions ranked by highest probabilities. Make sure the names of the 1000 categories from ImageNet are available so we can output the predictions through index: prob = torch.nn.functional.softmax(out, dim=1)[0] * 100_, indices = torch.sort(out, descending=True)return [(classes[idx], prob[idx].item()) for idx in indices[0][:5]] Now we can run the application by typing ‘streamlit run <the python file containing UI>’ in the command prompt/terminal. Let’s try two examples and see what the results look like. First example: Great! Golden retriever is at the top of the list, with high confidence score (~97). Let’s try another example: Green snake is at the top of the list! Again, its confidence score is quite high. One thing to be cautious here is that since the model was trained on ImageNet, its performance might not be as good for images outside of the 1000 categories. The natural next step after you create a web app is to deploy and host it. As an example, I deployed an Iris Classification app through Heroku and you can check it out through this Github page. In addition, if you are interested in other neural network models (VGG, Densenet, etc.), you can try upload different images and then compare their performances. Let’s quickly recap. We built a simple web app through Streamlit, and in this app, users can upload images to see the model’s top predictions as well as confidence scores. We also went through how to build a pretrained ResNet model through PyTorch. I hope you enjoy this blog post and please share any thought that you may have :) Check out my other post on sentiment classification on Yelp reviews using logistic regression:
[ { "code": null, "e": 207, "s": 171, "text": "You just developed a cool ML model." }, { "code": null, "e": 342, "s": 207, "text": "You are proud of it. You want to show it to your friends through a web demo so they can interact with your model and provide feedback." }, { "code": null, "e": 421, "s": 342, "text": "However, you are not familiar with common frameworks such as Django and Flask." }, { "code": null, "e": 513, "s": 421, "text": "You start to ask yourself: Is there a way to build a quick web demo with minimal framework?" }, { "code": null, "e": 647, "s": 513, "text": "What is Streamlit?How to make the UI?How to create the image classification model?What does the result look like?What can we do next?" }, { "code": null, "e": 666, "s": 647, "text": "What is Streamlit?" }, { "code": null, "e": 686, "s": 666, "text": "How to make the UI?" }, { "code": null, "e": 732, "s": 686, "text": "How to create the image classification model?" }, { "code": null, "e": 764, "s": 732, "text": "What does the result look like?" }, { "code": null, "e": 785, "s": 764, "text": "What can we do next?" }, { "code": null, "e": 891, "s": 785, "text": "In this post, I will walk through a quick example of how you can use Streamlit to build a simple web app." }, { "code": null, "e": 1105, "s": 891, "text": "Streamlit is an open-source Python library that makes it easy to build custom web apps for machine learning and data science [1]. Check out its gallery here to see some applications that other people have created." }, { "code": null, "e": 1464, "s": 1105, "text": "I have chosen image classification here as an example because computer vision (CV) is one of the most popular areas of AI currently, powered by deep learning algorithms. It also has a wide range of applications, such as classifying medical images to help doctors in disease diagnosis [2]. Learn more about image classification with deep learning models here." }, { "code": null, "e": 1682, "s": 1464, "text": "For demonstration purposes, I will use a pretrained ResNet model from PyTorch, and for the same task, you can always use other libraries (TensorFlow, Keras, etc.), other architecture, or even customize your own model." }, { "code": null, "e": 1736, "s": 1682, "text": "To see my full Python code, check out my Github page." }, { "code": null, "e": 1780, "s": 1736, "text": "Now without further ado, let’s get started!" }, { "code": null, "e": 1984, "s": 1780, "text": "The first step is to install the Streamlit library, and you can do that using the pip command. I recommend that you use a Python virtual environment to keep your dependencies separately for each project." }, { "code": null, "e": 2008, "s": 1984, "text": "$ pip install streamlit" }, { "code": null, "e": 2102, "s": 2008, "text": "After it is installed successfully, you can do a quick check with a simple ‘Hello World’ app:" }, { "code": null, "e": 2120, "s": 2102, "text": "$ streamlit hello" }, { "code": null, "e": 2284, "s": 2120, "text": "For our application, one key element is to enable users to upload images for the model to make predictions, and this can be done with the ‘file_uploader’ function:" }, { "code": null, "e": 2364, "s": 2284, "text": "import streamlit as stfile_up = st.file_uploader(\"Upload an image\", type=\"jpg\")" }, { "code": null, "e": 2463, "s": 2364, "text": "Make sure to specify the appropriate file type so it works properly with the classification model." }, { "code": null, "e": 2495, "s": 2463, "text": "Then we can display this image:" }, { "code": null, "e": 2609, "s": 2495, "text": "from PIL import Imageimage = Image.open(file_up)st.image(image, caption='Uploaded Image.', use_column_width=True)" }, { "code": null, "e": 2728, "s": 2609, "text": "Apart from that, we will also use ‘set_title’ to create a title for the app and ‘write’ to display prediction results." }, { "code": null, "e": 2871, "s": 2728, "text": "To use a pretrained model from PyTorch, make sure you have installed both ‘torch’ and ‘torchvision’ library. Now we can create a ResNet model:" }, { "code": null, "e": 2968, "s": 2871, "text": "from torchvision import models, transformsimport torchresnet = models.resnet101(pretrained=True)" }, { "code": null, "e": 3330, "s": 2968, "text": "To put it in simple terms, Residual Network (ResNet) is an improved Convolutional Neuron Network (CNN), trained in the well-known ImageNet database, and it has achieved great performance in CV tasks such as image classification and object detection. This particular model ‘resnet101’ means it has 101 layers (Deep!). Read more about ResNet and its variant here." }, { "code": null, "e": 3495, "s": 3330, "text": "After we create this model, we need to transform the input image through resizing, normalization, etc. Here we make use of the ‘transforms’ module in ‘torchvision’:" }, { "code": null, "e": 3704, "s": 3495, "text": "transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] )])" }, { "code": null, "e": 3821, "s": 3704, "text": "Note that the images are normalized according to its mean and standard deviation. See the documentation for details." }, { "code": null, "e": 3894, "s": 3821, "text": "Now we are able to load the image, pre-process it, and make predictions:" }, { "code": null, "e": 4001, "s": 3894, "text": "img = Image.open(image_path)batch_t = torch.unsqueeze(transform(img), 0)resnet.eval()out = resnet(batch_t)" }, { "code": null, "e": 4195, "s": 4001, "text": "Next, we can return the top 5 predictions ranked by highest probabilities. Make sure the names of the 1000 categories from ImageNet are available so we can output the predictions through index:" }, { "code": null, "e": 4363, "s": 4195, "text": "prob = torch.nn.functional.softmax(out, dim=1)[0] * 100_, indices = torch.sort(out, descending=True)return [(classes[idx], prob[idx].item()) for idx in indices[0][:5]]" }, { "code": null, "e": 4543, "s": 4363, "text": "Now we can run the application by typing ‘streamlit run <the python file containing UI>’ in the command prompt/terminal. Let’s try two examples and see what the results look like." }, { "code": null, "e": 4558, "s": 4543, "text": "First example:" }, { "code": null, "e": 4643, "s": 4558, "text": "Great! Golden retriever is at the top of the list, with high confidence score (~97)." }, { "code": null, "e": 4670, "s": 4643, "text": "Let’s try another example:" }, { "code": null, "e": 4752, "s": 4670, "text": "Green snake is at the top of the list! Again, its confidence score is quite high." }, { "code": null, "e": 4911, "s": 4752, "text": "One thing to be cautious here is that since the model was trained on ImageNet, its performance might not be as good for images outside of the 1000 categories." }, { "code": null, "e": 5105, "s": 4911, "text": "The natural next step after you create a web app is to deploy and host it. As an example, I deployed an Iris Classification app through Heroku and you can check it out through this Github page." }, { "code": null, "e": 5267, "s": 5105, "text": "In addition, if you are interested in other neural network models (VGG, Densenet, etc.), you can try upload different images and then compare their performances." }, { "code": null, "e": 5288, "s": 5267, "text": "Let’s quickly recap." }, { "code": null, "e": 5516, "s": 5288, "text": "We built a simple web app through Streamlit, and in this app, users can upload images to see the model’s top predictions as well as confidence scores. We also went through how to build a pretrained ResNet model through PyTorch." }, { "code": null, "e": 5598, "s": 5516, "text": "I hope you enjoy this blog post and please share any thought that you may have :)" } ]
How to use ‘while loop’ in Java?
A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop is − while(Boolean_expression) { // Statements } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value.When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.When the condition becomes false, program control passes to the line immediately following the loop. Here, the key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } } value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
[ { "code": null, "e": 1191, "s": 1062, "text": "A while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true." }, { "code": null, "e": 1223, "s": 1191, "text": "The syntax of a while loop is −" }, { "code": null, "e": 1270, "s": 1223, "text": "while(Boolean_expression) {\n // Statements\n}" }, { "code": null, "e": 1679, "s": 1270, "text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value.When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.When the condition becomes false, program control passes to the line immediately following the loop." }, { "code": null, "e": 1902, "s": 1679, "text": "Here, the key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 2119, "s": 1902, "text": "public class Test {\n public static void main(String args[]) {\n int x = 10;\n while( x < 20 ) {\n System.out.print(\"value of x : \" + x );\n x++;\n System.out.print(\"\\n\");\n }\n }\n}" }, { "code": null, "e": 2279, "s": 2119, "text": "value of x : 10\nvalue of x : 11\nvalue of x : 12\nvalue of x : 13\nvalue of x : 14\nvalue of x : 15\nvalue of x : 16\nvalue of x : 17\nvalue of x : 18\nvalue of x : 19" } ]
Managed Apache Airflow on AWS — New AWS Service For Data Pipelines | by Anna Geller | Towards Data Science
Apache Airflow has been initially released as an open-source product in 2015 [1]. Since its creation, it gained a lot of traction in the data engineering community due to its capability to develop data pipelines with Python, its extensibility, a wide range of operators, and an open-source community. Despite its popularity, deploying Airflow to a robust and secure production environment has always been challenging. In fact, there are companies (such as Astronomer), consultants (a.o. Polidea and GoDataDriven), and cloud services (such as Google Cloud Composer or many AWS Marketplace offerings) that specialized in offering enterprise support for deploying and managing Airflow environments. AWS now enters this market, too. The new fully managed service from AWS lets you create a production-ready Airflow environment within a few clicks in the management console. In this article, we’ll look at how it works and investigate how it differs from competing managed Airflow offerings. The main benefit and selling point of MWAA is convenience: a managed service with elastic worker-node capacity that allows you to deploy your DAGs without having to worry about the underlying infrastructure. This means that you no longer need to monitor and manually scale your Celery workers to meet your workflows' demand. So far, having elastic worker nodes with Airflow was only possible using KubernetesExecutor and KEDA (Kubernetes Event-Driven Autoscaler). With MWAA, you don’t choose Airflow executor — MWAA only supports CeleryExecutor with an autoscaling mechanism implemented under the hood. It’s no surprise that AWS-native SQS is leveraged as a message queue to process the scheduled Celery worker tasks. Airflow relies on a metadata database that stores information about your workflows. AWS utilizes RDS Aurora (Postgres) for that purpose. MWAA uses S3 as a storage layer for the code, i.e., DAG files, plugins code, and requirements.txt to install additional Python packages within the Airflow environment. Besides the autoscaling of worker node capacity, one of the most considerable advantages of MWAA is the fact that it’s a managed service. You don’t need to monitor webserver, worker nodes, and scheduler logs to ensure that all components within your environment are working — AWS is responsible for keeping your environment up and running at all times. The same is true for security patches and upgrades to new Airflow versions. The integration with other AWS services makes it easier to manage communication between Airflow and other services running within your VPC. For instance, instead of maintaining and manually rotating credentials, you can now leverage IAM roles for more robust management of permissions. Another useful feature is a centralized storage of configuration options. Airflow is configured to a large extent by setting variables in the airflow.cfg file. With MWAA, you can manage those settings directly from the management console. Normally, after having changed your configuration variables, you would have to restart your scheduler and worker nodes to apply the changes. With MWAA, it’s performed under the hood without bringing down your Airflow environment. The functionality of MWAA environments can be extended by using plugins — you simply need to upload plugins.zip to your S3 bucket to make custom operators, hooks, and sensors available to all your DAGs. Example structure of plugins.zip [3]: __init__.py |-- airflow_plugin.pyhooks/ |-- __init__.py |-- airflow_hook.pyoperators/ |-- __init__.py |-- airflow_operator.pysensors/ |-- __init__.py |-- airflow_sensor.py One of my favorite aspects of MWAA is how easy it is to configure logging to CloudWatch. Setting this up yourself would require a lot of work to configure a CloudWatch Agent on all instances to stream the logs to CloudWatch, and ensure proper log groups for all components (scheduler logs, worker nodes logs, web server logs, and the actual logs from your tasks). My second favorite feature is the integration of MWAA with IAM: only authorized IAM users can log into your Airflow UI. This is enabled by default without having to implement any custom Auth logic. When I open the link to the Airflow UI within a private browser window, we are not able to access the UI until we sign in with a user who has access to the AWS management console: From the security perspective, I would definitely recommend using MWAA rather than deploying Airfow yourself with EC2. AWS ensured that any data processed within MWAA is by default encrypted with KMS, and you get the Single-Sign-On that works out of the box. Similarly, you don’t need to worry about Security Groups, and a domain name is automatically assigned to your environment. From the DevOps perspective, MWAA is attractive since establishing a CI/CD pipeline for your DAGs is as easy as making sure that any push to the master branch triggers upload of the code to s3://airflow-BUCKET/dags. Lastly, AWS also promises support for containerized workloads with AWS Fargate and enables easy consolidated pricing for all your Airflow components by using tags assigned to your MWAA, S3, and CloudWatch resources. The overall process of creating an environment is to configure: VPC with two private subnets (via CloudFormation template), S3 bucket that will be used as a storage of your DAG files (it must be a bucket that starts with “airflow-” and with versioning enabled!), and optionally to upload plugins.zip to use custom operators, sensors, and hooks, as well as to upload requirements.txt to make additional Python packages available within this Airflow environment. In the demo below, I’m using the AWS management console to create the MWAA Airflow environment, including creating a VPC with two private subnets. Once the environment is available, you can upload a simple test DAG to the S3 bucket: s3://airflow-mwaa-dev. aws s3 cp ex_dag.py s3://airflow-mwaa-dev/dags/ After uploading to S3, we can find the DAG in the UI: As with any cloud service, you need to know what such a managed service will cost and how it differs from a self-managed environment. By deploying everything yourself and perfectly matching the compute resources to your needs, you could have some potential savings compared to a managed service. However, from my perspective, the autoscaling feature of your Celery worker nodes will most likely already provide cost savings compared to a self-hosted Airflow environment with idle compute resources. Also, one needs to consider the time savings that a managed service enables — you no longer need to spend time monitoring, patching, and restarting stuck webserver and scheduler instances, fixing broken Celery queues, and matching the worker nodes capacity to the needs of your workflows. AWS charges separately for the MWAA instance, worker nodes, and metadata database storage. Also, S3 and CloudWatch charges apply based on your region and usage. When you delete your Airflow MWAA environment, please make sure to delete the VPC that was configured within the default MWAA configuration via CloudFormation template, especially the NAT Gateway, for which the charges apply hourly. As long as you delete the VPC, make sure that the NAT Gateway is deleted as well to avoid any unnecessary charges. You can see it all from the VPC section in the management console: Managed services are great in terms of eliminating the headache related to maintaining the environment. However, the disadvantage is that: you can’t SSH to your scheduler, worker, or web server instances — the underlying servers are abstracted away from you, and you can’t SSH to them. Personally, I see no need to access those as long as everything is working, but some may view it as a constraint. This means that you can access the logs from those instances within CloudWatch, but you cannot, for instance, SSH to the instance and manually install some additional packages. you can’t access the metadata database directly to query your DAG information. From my perspective, nobody should be accessing this information directly, but rather via an API, so I find this abstraction useful. However, some people may see it as an undesirable constraint. Also, note that lots of information about your DAGs can be accessed from the Browse UI menu and by leveraging the API. using a specific Airflow version — at the time of writing, MWAA only supports the latest stable version, since AWS saw some security concerns in the previous Airflow versions [5]. If your workflows require a specific Airflow version, MWAA may not work for you. managing Python and code dependencies — this problem is not really tied to MWAA, but rather to Airflow, overall. If your code needs custom modules and packages, you may prefer to make use of DockerOperator or PythonVirtualEnvOperator. To learn more about those, you can have a look at the following articles: towardsdatascience.com medium.com There are many potential reasons why AWS may have decided to create this managed service. The first, quite an obvious reason, could be: So far, Google Cloud Platform has been (subjectively) offering the most comprehensive range of products with respect to data engineering, offering services such as Big Query (serverless, cost-effective, and ridiculously feature-rich DWH), Cloud Composer (Apache Airflow), Cloud Dataflow (Apache Beam), and many more. AWS could provide corresponding services for storing data such as Redshift (DWH), AWS Glue (metadata catalog), and Amazon Athena (serverless Presto), but the missing part was an orchestrator to glue those data services together. With MWAA, this missing piece can potentially be filled. Side note: You may say that AWS has Simple Workflow Service or Step Functions. But those services are hard to use to orchestrate data pipelines for ETL and ML, where most people prefer to do it in Python — the language of data. Apart from that, MWAA makes it easier to build ML pipelines using Sagemaker, as it allows you to combine all preprocessing and model training steps in a repeatable process. AWS consistently demonstrated its willingness to make open-source technologies more accessible and easier to manage. So far, AWS introduced managed services for: Kafka (Amazon MSK) Presto (Amazon Athena) Hadoop (Amazon EMR) Open-source relational databases such as Postgres, MySQL, MariaDB (RDS) Kubernetes (AWS EKS) Elasticsearch (Amazon Elasticsearch Service) Kibana (directly integrated within Elasticsearch service) Apache MXNet, PyTorch, Tensorflow & Jupyter (Sagemaker) Redis and Memcached (ElastiCache). Now, AWS is adding to this list Apache Airflow with the MWAA service. “Customers have told us they really like Apache Airflow because it speeds the development of their data processing and machine learning workflows, but they want it without the burden of scaling, operating, and securing servers,” — Jesse Dougherty, Vice President, Application Integration, AWS. [Source] AWS is customer-centric and security-aware. According to the above quote from the press release, many customers wanted to have Airflow on AWS, but it was too painful to deploy and maintain. To have a production-ready cloud-based Airflow environment, one needs to consider so many components that many customers likely decided to switch to competitors in order to get an easier and more reliable setup. Personally, I came across Airflow UIs that were publicly exposed to anyone without RBAC functionality. This happened because some people deployed Airflow via AWS Elastic Beanstalk without proper security mechanisms. This means that anyone in the world could access their environment, code, and data simply by using the admin-UI URL: http://URL-aws-region.elasticbeanstalk.com/admin/ Thanks to the managed service that introduces security by default (with encryption and Single-Sign-On), hopefully, fewer people will encounter such vulnerabilities in their Airflow deployments. While Astronomer is specialized in containerized Airflow environments deployed to a Kubernetes cluster, AWS MWAA is leveraging Celery executor and Celery workers deployed to managed EC2 instances running Amazon Linux AMI. Therefore, those two offerings are hard to compare against each other. From a pure feature perspective, Astronomer seems to be offering more due to their astro CLI that makes local development and code deployments easier, and additional features built on top, such as management of different team workspaces and dedicated enterprise support for Airflow. I doubt that adding a managed Airflow service to the AWS portfolio will put vendors such as Astronomer out of business. Companies still need and often prefer interacting with service providers (or consultants) specialized in one product that they know well. This is why Confluent is still doing great as a company despite the existence of a fully managed service Amazon MSK (Managed Streaming for Apache Kafka). However, providers such as Astronomer may lose significant market share due to the AWS-native managed service that eliminates the need for maintenance of a Kubernetes cluster. When comparing against Cloud Composer from GCP, the discussion becomes more interesting. While previously, companies, deciding which cloud provider to choose, might have preferred GCP due to their comprehensive data engineering services, they might now opt for AWS. Those services are also very similar in how they work — they both use CeleryExecutor for execution and object storage to store your DAG code, and they both let you easily create Airflow environments with a few clicks from the management console. The main difference between AWS MWAA and GCP Cloud Composer: while MWAA automatically scales the number of worker nodes, GCP does not — you need to monitor the worker nodes or Kubernetes pods yourself on GCP to manage the load of your workflows. Note: this comparison has been created based on publicly available information at the time of writing. Those services are evolving fast — make sure to validate this information with the respective service providers before making any decisions. In this article, we looked at the AWS fully managed service for Apache Airflow. We discussed its internal architecture, costs, benefits, and possible challenges when using that service. Additionally, we showed how to create your first environment from the management console. We discussed the possible reasons behind why AWS might have decided to incorporate Airflow into their range of supported open-source tools. Finally, we briefly compared MWAA against its competitors. To answer the question from the subtitle — is AWS MWAA worth trying? It boils down to whether you really want to use Airflow. If you are not sure whether Airflow suits your data engineering needs, have a look at those articles: towardsdatascience.com towardsdatascience.com Thank you for reading. References: [1] Wikipedia about Airflow [2] AWS Blog [3] AWS MWAA Docs on plugins [4] AWS Docs [5] AWS MWAA FAQ
[ { "code": null, "e": 589, "s": 171, "text": "Apache Airflow has been initially released as an open-source product in 2015 [1]. Since its creation, it gained a lot of traction in the data engineering community due to its capability to develop data pipelines with Python, its extensibility, a wide range of operators, and an open-source community. Despite its popularity, deploying Airflow to a robust and secure production environment has always been challenging." }, { "code": null, "e": 900, "s": 589, "text": "In fact, there are companies (such as Astronomer), consultants (a.o. Polidea and GoDataDriven), and cloud services (such as Google Cloud Composer or many AWS Marketplace offerings) that specialized in offering enterprise support for deploying and managing Airflow environments. AWS now enters this market, too." }, { "code": null, "e": 1158, "s": 900, "text": "The new fully managed service from AWS lets you create a production-ready Airflow environment within a few clicks in the management console. In this article, we’ll look at how it works and investigate how it differs from competing managed Airflow offerings." }, { "code": null, "e": 1622, "s": 1158, "text": "The main benefit and selling point of MWAA is convenience: a managed service with elastic worker-node capacity that allows you to deploy your DAGs without having to worry about the underlying infrastructure. This means that you no longer need to monitor and manually scale your Celery workers to meet your workflows' demand. So far, having elastic worker nodes with Airflow was only possible using KubernetesExecutor and KEDA (Kubernetes Event-Driven Autoscaler)." }, { "code": null, "e": 1876, "s": 1622, "text": "With MWAA, you don’t choose Airflow executor — MWAA only supports CeleryExecutor with an autoscaling mechanism implemented under the hood. It’s no surprise that AWS-native SQS is leveraged as a message queue to process the scheduled Celery worker tasks." }, { "code": null, "e": 2013, "s": 1876, "text": "Airflow relies on a metadata database that stores information about your workflows. AWS utilizes RDS Aurora (Postgres) for that purpose." }, { "code": null, "e": 2181, "s": 2013, "text": "MWAA uses S3 as a storage layer for the code, i.e., DAG files, plugins code, and requirements.txt to install additional Python packages within the Airflow environment." }, { "code": null, "e": 2610, "s": 2181, "text": "Besides the autoscaling of worker node capacity, one of the most considerable advantages of MWAA is the fact that it’s a managed service. You don’t need to monitor webserver, worker nodes, and scheduler logs to ensure that all components within your environment are working — AWS is responsible for keeping your environment up and running at all times. The same is true for security patches and upgrades to new Airflow versions." }, { "code": null, "e": 2896, "s": 2610, "text": "The integration with other AWS services makes it easier to manage communication between Airflow and other services running within your VPC. For instance, instead of maintaining and manually rotating credentials, you can now leverage IAM roles for more robust management of permissions." }, { "code": null, "e": 3365, "s": 2896, "text": "Another useful feature is a centralized storage of configuration options. Airflow is configured to a large extent by setting variables in the airflow.cfg file. With MWAA, you can manage those settings directly from the management console. Normally, after having changed your configuration variables, you would have to restart your scheduler and worker nodes to apply the changes. With MWAA, it’s performed under the hood without bringing down your Airflow environment." }, { "code": null, "e": 3606, "s": 3365, "text": "The functionality of MWAA environments can be extended by using plugins — you simply need to upload plugins.zip to your S3 bucket to make custom operators, hooks, and sensors available to all your DAGs. Example structure of plugins.zip [3]:" }, { "code": null, "e": 3799, "s": 3606, "text": "__init__.py |-- airflow_plugin.pyhooks/ |-- __init__.py |-- airflow_hook.pyoperators/ |-- __init__.py |-- airflow_operator.pysensors/ |-- __init__.py |-- airflow_sensor.py" }, { "code": null, "e": 4163, "s": 3799, "text": "One of my favorite aspects of MWAA is how easy it is to configure logging to CloudWatch. Setting this up yourself would require a lot of work to configure a CloudWatch Agent on all instances to stream the logs to CloudWatch, and ensure proper log groups for all components (scheduler logs, worker nodes logs, web server logs, and the actual logs from your tasks)." }, { "code": null, "e": 4541, "s": 4163, "text": "My second favorite feature is the integration of MWAA with IAM: only authorized IAM users can log into your Airflow UI. This is enabled by default without having to implement any custom Auth logic. When I open the link to the Airflow UI within a private browser window, we are not able to access the UI until we sign in with a user who has access to the AWS management console:" }, { "code": null, "e": 4923, "s": 4541, "text": "From the security perspective, I would definitely recommend using MWAA rather than deploying Airfow yourself with EC2. AWS ensured that any data processed within MWAA is by default encrypted with KMS, and you get the Single-Sign-On that works out of the box. Similarly, you don’t need to worry about Security Groups, and a domain name is automatically assigned to your environment." }, { "code": null, "e": 5139, "s": 4923, "text": "From the DevOps perspective, MWAA is attractive since establishing a CI/CD pipeline for your DAGs is as easy as making sure that any push to the master branch triggers upload of the code to s3://airflow-BUCKET/dags." }, { "code": null, "e": 5355, "s": 5139, "text": "Lastly, AWS also promises support for containerized workloads with AWS Fargate and enables easy consolidated pricing for all your Airflow components by using tags assigned to your MWAA, S3, and CloudWatch resources." }, { "code": null, "e": 5419, "s": 5355, "text": "The overall process of creating an environment is to configure:" }, { "code": null, "e": 5479, "s": 5419, "text": "VPC with two private subnets (via CloudFormation template)," }, { "code": null, "e": 5816, "s": 5479, "text": "S3 bucket that will be used as a storage of your DAG files (it must be a bucket that starts with “airflow-” and with versioning enabled!), and optionally to upload plugins.zip to use custom operators, sensors, and hooks, as well as to upload requirements.txt to make additional Python packages available within this Airflow environment." }, { "code": null, "e": 5963, "s": 5816, "text": "In the demo below, I’m using the AWS management console to create the MWAA Airflow environment, including creating a VPC with two private subnets." }, { "code": null, "e": 6072, "s": 5963, "text": "Once the environment is available, you can upload a simple test DAG to the S3 bucket: s3://airflow-mwaa-dev." }, { "code": null, "e": 6120, "s": 6072, "text": "aws s3 cp ex_dag.py s3://airflow-mwaa-dev/dags/" }, { "code": null, "e": 6174, "s": 6120, "text": "After uploading to S3, we can find the DAG in the UI:" }, { "code": null, "e": 6673, "s": 6174, "text": "As with any cloud service, you need to know what such a managed service will cost and how it differs from a self-managed environment. By deploying everything yourself and perfectly matching the compute resources to your needs, you could have some potential savings compared to a managed service. However, from my perspective, the autoscaling feature of your Celery worker nodes will most likely already provide cost savings compared to a self-hosted Airflow environment with idle compute resources." }, { "code": null, "e": 6962, "s": 6673, "text": "Also, one needs to consider the time savings that a managed service enables — you no longer need to spend time monitoring, patching, and restarting stuck webserver and scheduler instances, fixing broken Celery queues, and matching the worker nodes capacity to the needs of your workflows." }, { "code": null, "e": 7123, "s": 6962, "text": "AWS charges separately for the MWAA instance, worker nodes, and metadata database storage. Also, S3 and CloudWatch charges apply based on your region and usage." }, { "code": null, "e": 7538, "s": 7123, "text": "When you delete your Airflow MWAA environment, please make sure to delete the VPC that was configured within the default MWAA configuration via CloudFormation template, especially the NAT Gateway, for which the charges apply hourly. As long as you delete the VPC, make sure that the NAT Gateway is deleted as well to avoid any unnecessary charges. You can see it all from the VPC section in the management console:" }, { "code": null, "e": 7677, "s": 7538, "text": "Managed services are great in terms of eliminating the headache related to maintaining the environment. However, the disadvantage is that:" }, { "code": null, "e": 8115, "s": 7677, "text": "you can’t SSH to your scheduler, worker, or web server instances — the underlying servers are abstracted away from you, and you can’t SSH to them. Personally, I see no need to access those as long as everything is working, but some may view it as a constraint. This means that you can access the logs from those instances within CloudWatch, but you cannot, for instance, SSH to the instance and manually install some additional packages." }, { "code": null, "e": 8508, "s": 8115, "text": "you can’t access the metadata database directly to query your DAG information. From my perspective, nobody should be accessing this information directly, but rather via an API, so I find this abstraction useful. However, some people may see it as an undesirable constraint. Also, note that lots of information about your DAGs can be accessed from the Browse UI menu and by leveraging the API." }, { "code": null, "e": 8769, "s": 8508, "text": "using a specific Airflow version — at the time of writing, MWAA only supports the latest stable version, since AWS saw some security concerns in the previous Airflow versions [5]. If your workflows require a specific Airflow version, MWAA may not work for you." }, { "code": null, "e": 9078, "s": 8769, "text": "managing Python and code dependencies — this problem is not really tied to MWAA, but rather to Airflow, overall. If your code needs custom modules and packages, you may prefer to make use of DockerOperator or PythonVirtualEnvOperator. To learn more about those, you can have a look at the following articles:" }, { "code": null, "e": 9101, "s": 9078, "text": "towardsdatascience.com" }, { "code": null, "e": 9112, "s": 9101, "text": "medium.com" }, { "code": null, "e": 9202, "s": 9112, "text": "There are many potential reasons why AWS may have decided to create this managed service." }, { "code": null, "e": 9248, "s": 9202, "text": "The first, quite an obvious reason, could be:" }, { "code": null, "e": 9565, "s": 9248, "text": "So far, Google Cloud Platform has been (subjectively) offering the most comprehensive range of products with respect to data engineering, offering services such as Big Query (serverless, cost-effective, and ridiculously feature-rich DWH), Cloud Composer (Apache Airflow), Cloud Dataflow (Apache Beam), and many more." }, { "code": null, "e": 9851, "s": 9565, "text": "AWS could provide corresponding services for storing data such as Redshift (DWH), AWS Glue (metadata catalog), and Amazon Athena (serverless Presto), but the missing part was an orchestrator to glue those data services together. With MWAA, this missing piece can potentially be filled." }, { "code": null, "e": 10079, "s": 9851, "text": "Side note: You may say that AWS has Simple Workflow Service or Step Functions. But those services are hard to use to orchestrate data pipelines for ETL and ML, where most people prefer to do it in Python — the language of data." }, { "code": null, "e": 10252, "s": 10079, "text": "Apart from that, MWAA makes it easier to build ML pipelines using Sagemaker, as it allows you to combine all preprocessing and model training steps in a repeatable process." }, { "code": null, "e": 10414, "s": 10252, "text": "AWS consistently demonstrated its willingness to make open-source technologies more accessible and easier to manage. So far, AWS introduced managed services for:" }, { "code": null, "e": 10433, "s": 10414, "text": "Kafka (Amazon MSK)" }, { "code": null, "e": 10456, "s": 10433, "text": "Presto (Amazon Athena)" }, { "code": null, "e": 10476, "s": 10456, "text": "Hadoop (Amazon EMR)" }, { "code": null, "e": 10548, "s": 10476, "text": "Open-source relational databases such as Postgres, MySQL, MariaDB (RDS)" }, { "code": null, "e": 10569, "s": 10548, "text": "Kubernetes (AWS EKS)" }, { "code": null, "e": 10614, "s": 10569, "text": "Elasticsearch (Amazon Elasticsearch Service)" }, { "code": null, "e": 10672, "s": 10614, "text": "Kibana (directly integrated within Elasticsearch service)" }, { "code": null, "e": 10728, "s": 10672, "text": "Apache MXNet, PyTorch, Tensorflow & Jupyter (Sagemaker)" }, { "code": null, "e": 10763, "s": 10728, "text": "Redis and Memcached (ElastiCache)." }, { "code": null, "e": 10833, "s": 10763, "text": "Now, AWS is adding to this list Apache Airflow with the MWAA service." }, { "code": null, "e": 11136, "s": 10833, "text": "“Customers have told us they really like Apache Airflow because it speeds the development of their data processing and machine learning workflows, but they want it without the burden of scaling, operating, and securing servers,” — Jesse Dougherty, Vice President, Application Integration, AWS. [Source]" }, { "code": null, "e": 11538, "s": 11136, "text": "AWS is customer-centric and security-aware. According to the above quote from the press release, many customers wanted to have Airflow on AWS, but it was too painful to deploy and maintain. To have a production-ready cloud-based Airflow environment, one needs to consider so many components that many customers likely decided to switch to competitors in order to get an easier and more reliable setup." }, { "code": null, "e": 11871, "s": 11538, "text": "Personally, I came across Airflow UIs that were publicly exposed to anyone without RBAC functionality. This happened because some people deployed Airflow via AWS Elastic Beanstalk without proper security mechanisms. This means that anyone in the world could access their environment, code, and data simply by using the admin-UI URL:" }, { "code": null, "e": 11921, "s": 11871, "text": "http://URL-aws-region.elasticbeanstalk.com/admin/" }, { "code": null, "e": 12115, "s": 11921, "text": "Thanks to the managed service that introduces security by default (with encryption and Single-Sign-On), hopefully, fewer people will encounter such vulnerabilities in their Airflow deployments." }, { "code": null, "e": 12691, "s": 12115, "text": "While Astronomer is specialized in containerized Airflow environments deployed to a Kubernetes cluster, AWS MWAA is leveraging Celery executor and Celery workers deployed to managed EC2 instances running Amazon Linux AMI. Therefore, those two offerings are hard to compare against each other. From a pure feature perspective, Astronomer seems to be offering more due to their astro CLI that makes local development and code deployments easier, and additional features built on top, such as management of different team workspaces and dedicated enterprise support for Airflow." }, { "code": null, "e": 13279, "s": 12691, "text": "I doubt that adding a managed Airflow service to the AWS portfolio will put vendors such as Astronomer out of business. Companies still need and often prefer interacting with service providers (or consultants) specialized in one product that they know well. This is why Confluent is still doing great as a company despite the existence of a fully managed service Amazon MSK (Managed Streaming for Apache Kafka). However, providers such as Astronomer may lose significant market share due to the AWS-native managed service that eliminates the need for maintenance of a Kubernetes cluster." }, { "code": null, "e": 13791, "s": 13279, "text": "When comparing against Cloud Composer from GCP, the discussion becomes more interesting. While previously, companies, deciding which cloud provider to choose, might have preferred GCP due to their comprehensive data engineering services, they might now opt for AWS. Those services are also very similar in how they work — they both use CeleryExecutor for execution and object storage to store your DAG code, and they both let you easily create Airflow environments with a few clicks from the management console." }, { "code": null, "e": 13852, "s": 13791, "text": "The main difference between AWS MWAA and GCP Cloud Composer:" }, { "code": null, "e": 14037, "s": 13852, "text": "while MWAA automatically scales the number of worker nodes, GCP does not — you need to monitor the worker nodes or Kubernetes pods yourself on GCP to manage the load of your workflows." }, { "code": null, "e": 14281, "s": 14037, "text": "Note: this comparison has been created based on publicly available information at the time of writing. Those services are evolving fast — make sure to validate this information with the respective service providers before making any decisions." }, { "code": null, "e": 14756, "s": 14281, "text": "In this article, we looked at the AWS fully managed service for Apache Airflow. We discussed its internal architecture, costs, benefits, and possible challenges when using that service. Additionally, we showed how to create your first environment from the management console. We discussed the possible reasons behind why AWS might have decided to incorporate Airflow into their range of supported open-source tools. Finally, we briefly compared MWAA against its competitors." }, { "code": null, "e": 14984, "s": 14756, "text": "To answer the question from the subtitle — is AWS MWAA worth trying? It boils down to whether you really want to use Airflow. If you are not sure whether Airflow suits your data engineering needs, have a look at those articles:" }, { "code": null, "e": 15007, "s": 14984, "text": "towardsdatascience.com" }, { "code": null, "e": 15030, "s": 15007, "text": "towardsdatascience.com" }, { "code": null, "e": 15053, "s": 15030, "text": "Thank you for reading." }, { "code": null, "e": 15065, "s": 15053, "text": "References:" }, { "code": null, "e": 15093, "s": 15065, "text": "[1] Wikipedia about Airflow" }, { "code": null, "e": 15106, "s": 15093, "text": "[2] AWS Blog" }, { "code": null, "e": 15135, "s": 15106, "text": "[3] AWS MWAA Docs on plugins" }, { "code": null, "e": 15148, "s": 15135, "text": "[4] AWS Docs" } ]
Entering JSON data into MySQL?
Use the JSON data type to first set JSON data and then insert. Let us first create a table − mysql> create table DemoTable1876 ( EmployeeInformation JSON ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1876 values('{ '> "EmployeeData":{ '> "Name": "Chris", '> "Age": 27 '> } '> }' ); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1876 values('{ '> "EmployeeData":{ '> "Name": "David", '> "Age": 24 '> } '> }' ); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1876; This will produce the following output − +------------------------------------------------+ | EmployeeInformation | +------------------------------------------------+ | {"EmployeeData": {"Age": 27, "Name": "Chris"}} | | {"EmployeeData": {"Age": 24, "Name": "David"}} | +------------------------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "Use the JSON data type to first set JSON data and then insert. Let us first create a table −" }, { "code": null, "e": 1265, "s": 1155, "text": "mysql> create table DemoTable1876\n (\n EmployeeInformation JSON\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1321, "s": 1265, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1651, "s": 1321, "text": "mysql> insert into DemoTable1876 values('{\n '> \"EmployeeData\":{\n '> \"Name\": \"Chris\",\n '> \"Age\": 27\n '> }\n '> }'\n );\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1876 values('{\n '> \"EmployeeData\":{\n '> \"Name\": \"David\",\n '> \"Age\": 24\n '> }\n '> }'\n );\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1711, "s": 1651, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1747, "s": 1711, "text": "mysql> select * from DemoTable1876;" }, { "code": null, "e": 1788, "s": 1747, "text": "This will produce the following output −" }, { "code": null, "e": 2119, "s": 1788, "text": "+------------------------------------------------+\n| EmployeeInformation |\n+------------------------------------------------+\n| {\"EmployeeData\": {\"Age\": 27, \"Name\": \"Chris\"}} |\n| {\"EmployeeData\": {\"Age\": 24, \"Name\": \"David\"}} |\n+------------------------------------------------+\n2 rows in set (0.00 sec)" } ]
Tooltips with Python’s Matplotlib | by Thiago Carvalho | Towards Data Science
Allowing the user to hover the mouse or click a part of our visualization to get more context is excellent. And tooltips are a perfect way to save space in our chart. For example, for most scatter plots labelling every point can get tricky. You can color-code them and use a legend, but even that can get messy when there’s too much data. In this article, we’ll get a look at how to use event handlers and add tooltips to Matplotlib charts. For the following examples, we’ll use Matplotlib and Pandas. The data comes from the World Happiness Report. You can find a .xls on their website as ‘Data Panel’ or get a .csv from Kaggle. I’m using Jupyter Lab, so I need the magic command %matplotlib widget to correctly render the figure. You may need a different command such as %matplotlib notebook or %matplotlib ipympl depending on your version of Jupyter. If you’re running a script, you don’t need anything. import matplotlib.pyplot as pltimport pandas as pd%matplotlib widget# https://www.kaggle.com/ajaypalsinghlo/world-happiness-report-2021df = pd.read_csv('data/world-happiness-report.csv')df = df[df['year'] == 2020]x_name = 'Healthy life expectancy at birth'y_name = 'Freedom to make life choices'tooltip_name = 'Country name'x = df[x_name]y = df[y_name]tt = df[tooltip_name].valuesdf Let’s start with a simple scatter plot and build from it. fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x, y)plt.xlabel(x_name)plt.ylabel(y_name)plt.show() Now we’ll create a function that’ll be called when hovering our visualization. To start simple, we’ll add a text saying ‘Chart Ready’ and our function will change this text to blank when called. fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)annot_x = (plt.xlim()[1] + plt.xlim()[0])/2annot_y = (plt.ylim()[1] + plt.ylim()[0])/2txt = ax.text(annot_x, annot_y, "Chart Ready", ha='center', fontsize=36, color='#DD4012')def hover(event): txt.set_text("")fig.canvas.mpl_connect("motion_notify_event", hover)plt.show() We’re using Matplotlib’s “motion_notify_event” to detect the mouse movement, but there are plenty of other events you can try. button_press_event, button_release_event, draw_event, key_press_event, key_release_event, pick_event, resize_event, scroll_event, figure_enter_event, figure_leave_event, axes_enter_event, axes_leave_event, close_event. The idea is to draw the chart with all the elements we’ll use and then use the events to modify those elements. So even if some element is only displayed when a specific event is triggered, we still should define it outside of our function. The event we receive from mpl_connect at our hover function has some valuable properties; let’s try to get the XY coordinates of the mouse. plt.close('all')fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)lnx = plt.plot([60,60], [0,1.5], color='black', linewidth=0.3)lny = plt.plot([0,100], [1.5,1.5], color='black', linewidth=0.3)lnx[0].set_linestyle('None')lny[0].set_linestyle('None')plt.xlim(x.min()*0.95, x.max()*1.05)plt.ylim(y.min()*0.95, y.max()*1.05)def hover(event): lnx[0].set_data([event.xdata, event.xdata], [0, 1.5]) lnx[0].set_linestyle('--') lny[0].set_data([0,100], [event.ydata, event.ydata]) lny[0].set_linestyle('--') fig.canvas.mpl_connect("motion_notify_event", hover)plt.show() We added the lines, set their style to none, and when the cursor motion is detected, we change the data and style of that line to display it. Great! We know how to add and modify elements in our plot and detect the movement of the cursor. We’ll create a blank annotation and check if the mouse position is over one of the plotted points. When it is, we change the text, position, and visibility of the annotation accordingly. plt.close('all')fig, ax = plt.subplots(1, figsize=(12,6))# plot and labelssc = ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)# cursor grid lineslnx = plt.plot([60,60], [0,1.5], color='black', linewidth=0.3)lny = plt.plot([0,100], [1.5,1.5], color='black', linewidth=0.3)lnx[0].set_linestyle('None')lny[0].set_linestyle('None')# annotationannot = ax.annotate("", xy=(0,0), xytext=(5,5),textcoords="offset points")annot.set_visible(False)# xy limitsplt.xlim(x.min()*0.95, x.max()*1.05)plt.ylim(y.min()*0.95, y.max()*1.05)def hover(event): # check if event was in the axis if event.inaxes == ax: # draw lines and make sure they're visible lnx[0].set_data([event.xdata, event.xdata], [0, 1.5]) lnx[0].set_linestyle('--') lny[0].set_data([0,100], [event.ydata, event.ydata]) lny[0].set_linestyle('--') lnx[0].set_visible(True) lny[0].set_visible(True) # get the points contained in the event cont, ind = sc.contains(event) if cont: # change annotation position annot.xy = (event.xdata, event.ydata) # write the name of every point contained in the event annot.set_text("{}".format(', '.join([tt[n] for n in ind["ind"]]))) annot.set_visible(True) else: annot.set_visible(False) else: lnx[0].set_visible(False) lny[0].set_visible(False)fig.canvas.mpl_connect("motion_notify_event", hover)plt.show() There it is! We have a tooltip on our chart, but it wasn’t exactly straightforward to build. We’re drawing a scatter plot that returns a PathCollection object with the convenient method .contains(). Matplotlib returns different objects for different visualizations .bar will return BarContainer, .plot will return a list of Line2D, and so on. That means we’ll have to develop a different solution to add tooltips for each visualization. The freedom to develop how your chart will behave for each event is excellent. But depending on how complex your visualization is, this might test your patience. Luckily there are other solutions for adding tooltips to Matplotlib. This handy package facilitates mouse events in Matplotlib with some easy-to-use methods. They also have lots of examples that are easy to customize. So instead of digging Matplotlib’s documents and trying to figure out your way. You can replace a couple of lines from the examples and get your tooltips in no time. import matplotlib.pyplot as pltimport mplcursors%matplotlib widgetfig, ax = plt.subplots()sc = ax.scatter(x,y)# by default the tooltip is displayed "onclick"# we can change it by setting hover to Truecursor = mplcursors.cursor(sc, hover=True)# by default the annotation displays the xy positions# this is to change it to the countries name@cursor.connect("add")def on_add(sel): sel.annotation.set(text=tt[sel.target.index])plt.show() df = df.sort_values('Log GDP per capita')df = df[df['Log GDP per capita'].notna()]fig, ax = plt.subplots(figsize=(12,6))ax.bar(df['Country name'], df['Log GDP per capita'], align="center")plt.xticks([])cursor = mplcursors.cursor(hover=mplcursors.HoverMode.Transient)@cursor.connect("add")def on_add(sel): sel.annotation.set(text=df.iloc[sel.target.index]['Country name'])plt.show() Overall, adding tooltips to Matplotlib charts can quickly get complex and even with Mplcursors, it isn’t as easy as it could be. The way I see it is, we can get around with Mplcursors to add some extra functionalities to your visualization without struggling so much. If you are willing to put some more effort into it, you can build the most complex visualizations with all the available events Matplotlib has. There are other options with Python, such as Plotly for designing interactive data visualizations; or MplD3, which adds some extra functionalities to Matplotlib charts by converting them into D3.js. Thanks for reading! All images are my own. Feel free to use them.
[ { "code": null, "e": 339, "s": 172, "text": "Allowing the user to hover the mouse or click a part of our visualization to get more context is excellent. And tooltips are a perfect way to save space in our chart." }, { "code": null, "e": 511, "s": 339, "text": "For example, for most scatter plots labelling every point can get tricky. You can color-code them and use a legend, but even that can get messy when there’s too much data." }, { "code": null, "e": 613, "s": 511, "text": "In this article, we’ll get a look at how to use event handlers and add tooltips to Matplotlib charts." }, { "code": null, "e": 802, "s": 613, "text": "For the following examples, we’ll use Matplotlib and Pandas. The data comes from the World Happiness Report. You can find a .xls on their website as ‘Data Panel’ or get a .csv from Kaggle." }, { "code": null, "e": 904, "s": 802, "text": "I’m using Jupyter Lab, so I need the magic command %matplotlib widget to correctly render the figure." }, { "code": null, "e": 1079, "s": 904, "text": "You may need a different command such as %matplotlib notebook or %matplotlib ipympl depending on your version of Jupyter. If you’re running a script, you don’t need anything." }, { "code": null, "e": 1462, "s": 1079, "text": "import matplotlib.pyplot as pltimport pandas as pd%matplotlib widget# https://www.kaggle.com/ajaypalsinghlo/world-happiness-report-2021df = pd.read_csv('data/world-happiness-report.csv')df = df[df['year'] == 2020]x_name = 'Healthy life expectancy at birth'y_name = 'Freedom to make life choices'tooltip_name = 'Country name'x = df[x_name]y = df[y_name]tt = df[tooltip_name].valuesdf" }, { "code": null, "e": 1520, "s": 1462, "text": "Let’s start with a simple scatter plot and build from it." }, { "code": null, "e": 1624, "s": 1520, "text": "fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x, y)plt.xlabel(x_name)plt.ylabel(y_name)plt.show()" }, { "code": null, "e": 1703, "s": 1624, "text": "Now we’ll create a function that’ll be called when hovering our visualization." }, { "code": null, "e": 1819, "s": 1703, "text": "To start simple, we’ll add a text saying ‘Chart Ready’ and our function will change this text to blank when called." }, { "code": null, "e": 2200, "s": 1819, "text": "fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)annot_x = (plt.xlim()[1] + plt.xlim()[0])/2annot_y = (plt.ylim()[1] + plt.ylim()[0])/2txt = ax.text(annot_x, annot_y, \"Chart Ready\", ha='center', fontsize=36, color='#DD4012')def hover(event): txt.set_text(\"\")fig.canvas.mpl_connect(\"motion_notify_event\", hover)plt.show()" }, { "code": null, "e": 2327, "s": 2200, "text": "We’re using Matplotlib’s “motion_notify_event” to detect the mouse movement, but there are plenty of other events you can try." }, { "code": null, "e": 2546, "s": 2327, "text": "button_press_event, button_release_event, draw_event, key_press_event, key_release_event, pick_event, resize_event, scroll_event, figure_enter_event, figure_leave_event, axes_enter_event, axes_leave_event, close_event." }, { "code": null, "e": 2658, "s": 2546, "text": "The idea is to draw the chart with all the elements we’ll use and then use the events to modify those elements." }, { "code": null, "e": 2787, "s": 2658, "text": "So even if some element is only displayed when a specific event is triggered, we still should define it outside of our function." }, { "code": null, "e": 2927, "s": 2787, "text": "The event we receive from mpl_connect at our hover function has some valuable properties; let’s try to get the XY coordinates of the mouse." }, { "code": null, "e": 3546, "s": 2927, "text": "plt.close('all')fig, ax = plt.subplots(1, figsize=(12,6))ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)lnx = plt.plot([60,60], [0,1.5], color='black', linewidth=0.3)lny = plt.plot([0,100], [1.5,1.5], color='black', linewidth=0.3)lnx[0].set_linestyle('None')lny[0].set_linestyle('None')plt.xlim(x.min()*0.95, x.max()*1.05)plt.ylim(y.min()*0.95, y.max()*1.05)def hover(event): lnx[0].set_data([event.xdata, event.xdata], [0, 1.5]) lnx[0].set_linestyle('--') lny[0].set_data([0,100], [event.ydata, event.ydata]) lny[0].set_linestyle('--') fig.canvas.mpl_connect(\"motion_notify_event\", hover)plt.show()" }, { "code": null, "e": 3688, "s": 3546, "text": "We added the lines, set their style to none, and when the cursor motion is detected, we change the data and style of that line to display it." }, { "code": null, "e": 3785, "s": 3688, "text": "Great! We know how to add and modify elements in our plot and detect the movement of the cursor." }, { "code": null, "e": 3972, "s": 3785, "text": "We’ll create a blank annotation and check if the mouse position is over one of the plotted points. When it is, we change the text, position, and visibility of the annotation accordingly." }, { "code": null, "e": 5447, "s": 3972, "text": "plt.close('all')fig, ax = plt.subplots(1, figsize=(12,6))# plot and labelssc = ax.scatter(x,y)plt.xlabel(x_name)plt.ylabel(y_name)# cursor grid lineslnx = plt.plot([60,60], [0,1.5], color='black', linewidth=0.3)lny = plt.plot([0,100], [1.5,1.5], color='black', linewidth=0.3)lnx[0].set_linestyle('None')lny[0].set_linestyle('None')# annotationannot = ax.annotate(\"\", xy=(0,0), xytext=(5,5),textcoords=\"offset points\")annot.set_visible(False)# xy limitsplt.xlim(x.min()*0.95, x.max()*1.05)plt.ylim(y.min()*0.95, y.max()*1.05)def hover(event): # check if event was in the axis if event.inaxes == ax: # draw lines and make sure they're visible lnx[0].set_data([event.xdata, event.xdata], [0, 1.5]) lnx[0].set_linestyle('--') lny[0].set_data([0,100], [event.ydata, event.ydata]) lny[0].set_linestyle('--') lnx[0].set_visible(True) lny[0].set_visible(True) # get the points contained in the event cont, ind = sc.contains(event) if cont: # change annotation position annot.xy = (event.xdata, event.ydata) # write the name of every point contained in the event annot.set_text(\"{}\".format(', '.join([tt[n] for n in ind[\"ind\"]]))) annot.set_visible(True) else: annot.set_visible(False) else: lnx[0].set_visible(False) lny[0].set_visible(False)fig.canvas.mpl_connect(\"motion_notify_event\", hover)plt.show()" }, { "code": null, "e": 5460, "s": 5447, "text": "There it is!" }, { "code": null, "e": 5646, "s": 5460, "text": "We have a tooltip on our chart, but it wasn’t exactly straightforward to build. We’re drawing a scatter plot that returns a PathCollection object with the convenient method .contains()." }, { "code": null, "e": 5790, "s": 5646, "text": "Matplotlib returns different objects for different visualizations .bar will return BarContainer, .plot will return a list of Line2D, and so on." }, { "code": null, "e": 5884, "s": 5790, "text": "That means we’ll have to develop a different solution to add tooltips for each visualization." }, { "code": null, "e": 6046, "s": 5884, "text": "The freedom to develop how your chart will behave for each event is excellent. But depending on how complex your visualization is, this might test your patience." }, { "code": null, "e": 6115, "s": 6046, "text": "Luckily there are other solutions for adding tooltips to Matplotlib." }, { "code": null, "e": 6204, "s": 6115, "text": "This handy package facilitates mouse events in Matplotlib with some easy-to-use methods." }, { "code": null, "e": 6430, "s": 6204, "text": "They also have lots of examples that are easy to customize. So instead of digging Matplotlib’s documents and trying to figure out your way. You can replace a couple of lines from the examples and get your tooltips in no time." }, { "code": null, "e": 6867, "s": 6430, "text": "import matplotlib.pyplot as pltimport mplcursors%matplotlib widgetfig, ax = plt.subplots()sc = ax.scatter(x,y)# by default the tooltip is displayed \"onclick\"# we can change it by setting hover to Truecursor = mplcursors.cursor(sc, hover=True)# by default the annotation displays the xy positions# this is to change it to the countries name@cursor.connect(\"add\")def on_add(sel): sel.annotation.set(text=tt[sel.target.index])plt.show()" }, { "code": null, "e": 7252, "s": 6867, "text": "df = df.sort_values('Log GDP per capita')df = df[df['Log GDP per capita'].notna()]fig, ax = plt.subplots(figsize=(12,6))ax.bar(df['Country name'], df['Log GDP per capita'], align=\"center\")plt.xticks([])cursor = mplcursors.cursor(hover=mplcursors.HoverMode.Transient)@cursor.connect(\"add\")def on_add(sel): sel.annotation.set(text=df.iloc[sel.target.index]['Country name'])plt.show()" }, { "code": null, "e": 7381, "s": 7252, "text": "Overall, adding tooltips to Matplotlib charts can quickly get complex and even with Mplcursors, it isn’t as easy as it could be." }, { "code": null, "e": 7664, "s": 7381, "text": "The way I see it is, we can get around with Mplcursors to add some extra functionalities to your visualization without struggling so much. If you are willing to put some more effort into it, you can build the most complex visualizations with all the available events Matplotlib has." }, { "code": null, "e": 7863, "s": 7664, "text": "There are other options with Python, such as Plotly for designing interactive data visualizations; or MplD3, which adds some extra functionalities to Matplotlib charts by converting them into D3.js." }, { "code": null, "e": 7883, "s": 7863, "text": "Thanks for reading!" } ]
Matplotlib.axes.Axes.get_lines() in Python - GeeksforGeeks
27 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.get_lines() function in axes module of matplotlib library is used to return a list of lines contained by the Axes Syntax: Axes.get_lines(self) Parameters: This method does not accept any parameters. Returns: This method return a list of lines contained by the Axes. Below examples illustrate the matplotlib.axes.Axes.get_lines() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt N_points = 100000x = np.random.randn(N_points)y = .4 * x + np.random.randn(100000) + 5 fig, ax = plt.subplots()ax.hist2d(x, y, bins = 100, norm = colors.LogNorm(), cmap ="Greens") w = list(ax.get_lines())if len(w)== 0: ax.text(-2, 8.5, "No line contained by the Axes \n")else: ax.text(-3, 8.5, "List of the lines contained by the Axes \n") x = 8.5 for i in w: ax.text(-3, x-0.5, str(i)) x-= 0.5 fig.suptitle('matplotlib.axes.Axes.get_lines() \function Example', fontweight ="bold") plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as mpatches fig, ax = plt.subplots()x, y = 10 * np.random.rand(2, 1000)ax.plot(x, y, 'go', alpha = 0.2) circ = mpatches.Circle((0.5, 0.5), 0.25, transform = ax.transAxes, facecolor ='blue', alpha = 0.75) ax.add_patch(circ) w = list(ax.get_lines()) if len(w)== 0: ax.text(1, 8.5, "No line contained by the Axes \n") else: ax.text(1, 8.5, "List of the lines contained by the Axes \n") x = 8.5 for i in w: ax.text(1, x-0.5, str(i)) x-= 0.5 fig.suptitle('matplotlib.axes.Axes.get_lines() \function Example', fontweight ="bold") plt.show() Output: Matplotlib axes-class Python-matplotlib 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 Create a Pandas DataFrame from Lists Reading and Writing to text files in Python sum() function in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24876, "s": 24848, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25176, "s": 24876, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 25299, "s": 25176, "text": "The Axes.get_lines() function in axes module of matplotlib library is used to return a list of lines contained by the Axes" }, { "code": null, "e": 25328, "s": 25299, "text": "Syntax: Axes.get_lines(self)" }, { "code": null, "e": 25384, "s": 25328, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 25451, "s": 25384, "text": "Returns: This method return a list of lines contained by the Axes." }, { "code": null, "e": 25543, "s": 25451, "text": "Below examples illustrate the matplotlib.axes.Axes.get_lines() function in matplotlib.axes:" }, { "code": null, "e": 25554, "s": 25543, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionfrom matplotlib import colorsfrom matplotlib.ticker import PercentFormatterimport numpy as npimport matplotlib.pyplot as plt N_points = 100000x = np.random.randn(N_points)y = .4 * x + np.random.randn(100000) + 5 fig, ax = plt.subplots()ax.hist2d(x, y, bins = 100, norm = colors.LogNorm(), cmap =\"Greens\") w = list(ax.get_lines())if len(w)== 0: ax.text(-2, 8.5, \"No line contained by the Axes \\n\")else: ax.text(-3, 8.5, \"List of the lines contained by the Axes \\n\") x = 8.5 for i in w: ax.text(-3, x-0.5, str(i)) x-= 0.5 fig.suptitle('matplotlib.axes.Axes.get_lines() \\function Example', fontweight =\"bold\") plt.show()", "e": 26297, "s": 25554, "text": null }, { "code": null, "e": 26305, "s": 26297, "text": "Output:" }, { "code": null, "e": 26316, "s": 26305, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.patches as mpatches fig, ax = plt.subplots()x, y = 10 * np.random.rand(2, 1000)ax.plot(x, y, 'go', alpha = 0.2) circ = mpatches.Circle((0.5, 0.5), 0.25, transform = ax.transAxes, facecolor ='blue', alpha = 0.75) ax.add_patch(circ) w = list(ax.get_lines()) if len(w)== 0: ax.text(1, 8.5, \"No line contained by the Axes \\n\") else: ax.text(1, 8.5, \"List of the lines contained by the Axes \\n\") x = 8.5 for i in w: ax.text(1, x-0.5, str(i)) x-= 0.5 fig.suptitle('matplotlib.axes.Axes.get_lines() \\function Example', fontweight =\"bold\") plt.show()", "e": 27121, "s": 26316, "text": null }, { "code": null, "e": 27129, "s": 27121, "text": "Output:" }, { "code": null, "e": 27151, "s": 27129, "text": "Matplotlib axes-class" }, { "code": null, "e": 27169, "s": 27151, "text": "Python-matplotlib" }, { "code": null, "e": 27176, "s": 27169, "text": "Python" }, { "code": null, "e": 27274, "s": 27176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27283, "s": 27274, "text": "Comments" }, { "code": null, "e": 27296, "s": 27283, "text": "Old Comments" }, { "code": null, "e": 27314, "s": 27296, "text": "Python Dictionary" }, { "code": null, "e": 27349, "s": 27314, "text": "Read a file line by line in Python" }, { "code": null, "e": 27371, "s": 27349, "text": "Enumerate() in Python" }, { "code": null, "e": 27403, "s": 27371, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27445, "s": 27403, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27482, "s": 27445, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27526, "s": 27482, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27551, "s": 27526, "text": "sum() function in Python" }, { "code": null, "e": 27580, "s": 27551, "text": "*args and **kwargs in Python" } ]
MySQL query to count rows in multiple tables
Let us first create a table − mysql> create table DemoTable1 (FirstName varchar(100)); Query OK, 0 rows affected (0.54 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values('Bob'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1 values('James'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1 values('John'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1 values('David'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement − mysql> select *from DemoTable1; This will produce the following output - +-----------+ | FirstName | +-----------+ | Bob | | James | | John | | David | +-----------+ 4 rows in set (0.00 sec) Here is the query to create second table − mysql> create table DemoTable2 (Marks int); Query OK, 0 rows affected (0.65 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values(98); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(89); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable2 values(67); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(34); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable2 values(32); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable2 values(42); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable2; This will produce the following output - +-------+ | Marks | +-------+ | 98 | | 89 | | 67 | | 34 | | 32 | | 42 | +-------+ 6 rows in set (0.00 sec) Here is the query to count rows in multiple tables − mysql> select (select count(*) from DemoTable1) AS First_Table_Row, (select count(*) from DemoTable2) AS Second_Table_Row; This will produce the following output - +-----------------+------------------+ | First_Table_Row | Second_Table_Row | +-----------------+------------------+ | 4 | 6 | +-----------------+------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1186, "s": 1092, "text": "mysql> create table DemoTable1 (FirstName varchar(100));\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1242, "s": 1186, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1571, "s": 1242, "text": "mysql> insert into DemoTable1 values('Bob');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable1 values('James');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1 values('John');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable1 values('David');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 1631, "s": 1571, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1663, "s": 1631, "text": "mysql> select *from DemoTable1;" }, { "code": null, "e": 1704, "s": 1663, "text": "This will produce the following output -" }, { "code": null, "e": 1841, "s": 1704, "text": "+-----------+\n| FirstName |\n+-----------+\n| Bob |\n| James |\n| John |\n| David |\n+-----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1884, "s": 1841, "text": "Here is the query to create second table −" }, { "code": null, "e": 1965, "s": 1884, "text": "mysql> create table DemoTable2 (Marks int);\nQuery OK, 0 rows affected (0.65 sec)" }, { "code": null, "e": 2021, "s": 1965, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2489, "s": 2021, "text": "mysql> insert into DemoTable2 values(98);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable2 values(89);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable2 values(67);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable2 values(34);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable2 values(32);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable2 values(42);\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2549, "s": 2489, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2581, "s": 2549, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2622, "s": 2581, "text": "This will produce the following output -" }, { "code": null, "e": 2747, "s": 2622, "text": "+-------+\n| Marks |\n+-------+\n| 98 |\n| 89 |\n| 67 |\n| 34 |\n| 32 |\n| 42 |\n+-------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2800, "s": 2747, "text": "Here is the query to count rows in multiple tables −" }, { "code": null, "e": 2929, "s": 2800, "text": "mysql> select\n (select count(*) from DemoTable1) AS First_Table_Row,\n (select count(*) from DemoTable2) AS Second_Table_Row;" }, { "code": null, "e": 2970, "s": 2929, "text": "This will produce the following output -" }, { "code": null, "e": 3189, "s": 2970, "text": "+-----------------+------------------+\n| First_Table_Row | Second_Table_Row |\n+-----------------+------------------+\n| 4 | 6 |\n+-----------------+------------------+\n1 row in set (0.00 sec)" } ]
MPI - Distributed Computing made easy - GeeksforGeeks
01 Apr, 2020 The Underlying Problem To make things easier, let’s directly jump to some statistics: Facebook, currently, has 1.5 billion active monthly users. Google performs at least 1 trillion searches per year. About 48 hours of video is uploaded in Youtube every minute. With such a high demand, I do believe that a single system would be unable to handle the processing. Thus, comes the need for Distributed Systems. What is Distributed Computing? A distributed system consists of a collection of autonomous computers, connected through a network and distribution middleware, which enables computers to coordinate their activities and to share the resources of the system, so that users perceive the system as a single, integrated computing facility. Let us say about Google Web Server, from users perspective while they submit the searched query, they assume google web server as a single system. However, behind the curtain, google has built a lot of servers which is distributed (geographically and computationally) to give us the result within few seconds. Advantages of Distributed Computing? Highly efficient Scalability Less tolerant to failures High Availability Let us look at an example where we save the computational time by using distributed computing. For eg. If we have an array, a, having n elements, a=[1, 2, 3, 4, 5, 6] We want to sum all the elements of the array and output it. Now, let us assume that there are 1020 elements in the array and the time to compute the sum is x. If we now divide the array in 3 parts, a1, a2 and a3 where a1 = { Set of elements where modulo(element from a) == 0 } a2 = { Set of elements where modulo(element from a) == 1 } a3 = { Set of elements where modulo(element from a) == 2 } We will send these 3 arrays to 3 different processes for computing the sum of these individual processes. On an average, let’s assume that each array has n/3 elements. Thus, time taken by each process will also reduces to x/3. Since these process will be running in parallel, the three “x/3” will be computed simultaneously and sum of each array is returned to the main process. In the end, we can compute the final sum of a by summing up the individual sum of the arrays: a1, a2 and a3. Thus, we are able to reduce the time from x to x/3, if we are running the processed simultaneously. What is MPI? Message Passing Interface (MPI) is a standardized and portable message-passing system developed for distributed and parallel computing. MPI provides parallel hardware vendors with a clearly defined base set of routines that can be efficiently implemented. As a result, hardware vendors can build upon this collection of standard low-level routines to create higher-level routines for the distributed-memory communication environment supplied with their parallel machines. MPI gives user the flexibility of calling set of routines from C, C++, Fortran, C#, Java or Python. The advantages of MPI over older message passing libraries are portability (because MPI has been implemented for almost every distributed memory architecture) and speed (because each implementation is in principle optimized for the hardware on which it runs) The advantages of MPI over other message passing framework is portability and speed. It has been implemented for almost every distributed memory architecture and each implementation is in principle optimized for the hardware on which it runs. Even though there are options available for multiple languages, Python is the most preferred one due to simplicity, ease of writing the code. So, now, we will now look at how to install MPI on ubuntu 14.10. Install MPI on Ubuntu 1) Step No. 1: Copy the following line of code in your terminal to install NumPy, a package for all scientific computing in python. sudo apt-get install python-numpy 2) After successful completion of the above step, execute the following commands to update the system and install the pip package. sudo apt-get update sudo apt-get -y install python-pip 3) Now, we will download the doc for the latest version of the MPI. sudo apt-get install libcr-dev mpich2 mpich2-doc 4) Enter the command to download MPI using pip for python sudo pip install mpi4py MPI is successfully installed now. Sometimes, a problem might pop up while clearing up the packages after MPI has been installed due to absence of dev tools in python. Yo can install them using the following command: sudo apt-get install python-dev MPI on Windows/MAC For Windows/MAC user, they can visit the following link and download the .zip file and unzip and execute it: MPI framework Tutorials Following installation, you can refer to the following documentation for using MPI using python. https://mpi4py.scipy.org/docs/usrman/tutorial.html References https://www.open-mpi.org/ https://en.wikipedia.org/wiki/Message_Passing_Interface About the Author: Anurag Mishra currently a 3rd year B.Tech student is an avid software follower and a full stack web developer. His keen interest lies in web development, NLP and networking. If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks. srinam GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers A Freshers Guide To Programming Top 10 System Design Interview Questions and Answers Supervised and Unsupervised learning XML parsing in Python Working with PDF files in Python Genetic Algorithms Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 24538, "s": 24510, "text": "\n01 Apr, 2020" }, { "code": null, "e": 24563, "s": 24540, "text": "The Underlying Problem" }, { "code": null, "e": 24626, "s": 24563, "text": "To make things easier, let’s directly jump to some statistics:" }, { "code": null, "e": 24685, "s": 24626, "text": "Facebook, currently, has 1.5 billion active monthly users." }, { "code": null, "e": 24740, "s": 24685, "text": "Google performs at least 1 trillion searches per year." }, { "code": null, "e": 24801, "s": 24740, "text": "About 48 hours of video is uploaded in Youtube every minute." }, { "code": null, "e": 24948, "s": 24801, "text": "With such a high demand, I do believe that a single system would be unable to handle the processing. Thus, comes the need for Distributed Systems." }, { "code": null, "e": 24979, "s": 24948, "text": "What is Distributed Computing?" }, { "code": null, "e": 25282, "s": 24979, "text": "A distributed system consists of a collection of autonomous computers, connected through a network and distribution middleware, which enables computers to coordinate their activities and to share the resources of the system, so that users perceive the system as a single, integrated computing facility." }, { "code": null, "e": 25592, "s": 25282, "text": "Let us say about Google Web Server, from users perspective while they submit the searched query, they assume google web server as a single system. However, behind the curtain, google has built a lot of servers which is distributed (geographically and computationally) to give us the result within few seconds." }, { "code": null, "e": 25629, "s": 25592, "text": "Advantages of Distributed Computing?" }, { "code": null, "e": 25646, "s": 25629, "text": "Highly efficient" }, { "code": null, "e": 25658, "s": 25646, "text": "Scalability" }, { "code": null, "e": 25684, "s": 25658, "text": "Less tolerant to failures" }, { "code": null, "e": 25702, "s": 25684, "text": "High Availability" }, { "code": null, "e": 25797, "s": 25702, "text": "Let us look at an example where we save the computational time by using distributed computing." }, { "code": null, "e": 25869, "s": 25797, "text": "For eg. If we have an array, a, having n elements, a=[1, 2, 3, 4, 5, 6]" }, { "code": null, "e": 26028, "s": 25869, "text": "We want to sum all the elements of the array and output it. Now, let us assume that there are 1020 elements in the array and the time to compute the sum is x." }, { "code": null, "e": 26087, "s": 26028, "text": "If we now divide the array in 3 parts, a1, a2 and a3 where" }, { "code": null, "e": 26146, "s": 26087, "text": "a1 = { Set of elements where modulo(element from a) == 0 }" }, { "code": null, "e": 26205, "s": 26146, "text": "a2 = { Set of elements where modulo(element from a) == 1 }" }, { "code": null, "e": 26264, "s": 26205, "text": "a3 = { Set of elements where modulo(element from a) == 2 }" }, { "code": null, "e": 26752, "s": 26264, "text": "We will send these 3 arrays to 3 different processes for computing the sum of these individual processes. On an average, let’s assume that each array has n/3 elements. Thus, time taken by each process will also reduces to x/3. Since these process will be running in parallel, the three “x/3” will be computed simultaneously and sum of each array is returned to the main process. In the end, we can compute the final sum of a by summing up the individual sum of the arrays: a1, a2 and a3." }, { "code": null, "e": 26852, "s": 26752, "text": "Thus, we are able to reduce the time from x to x/3, if we are running the processed simultaneously." }, { "code": null, "e": 26865, "s": 26852, "text": "What is MPI?" }, { "code": null, "e": 27337, "s": 26865, "text": "Message Passing Interface (MPI) is a standardized and portable message-passing system developed for distributed and parallel computing. MPI provides parallel hardware vendors with a clearly defined base set of routines that can be efficiently implemented. As a result, hardware vendors can build upon this collection of standard low-level routines to create higher-level routines for the distributed-memory communication environment supplied with their parallel machines." }, { "code": null, "e": 27696, "s": 27337, "text": "MPI gives user the flexibility of calling set of routines from C, C++, Fortran, C#, Java or Python. The advantages of MPI over older message passing libraries are portability (because MPI has been implemented for almost every distributed memory architecture) and speed (because each implementation is in principle optimized for the hardware on which it runs)" }, { "code": null, "e": 27939, "s": 27696, "text": "The advantages of MPI over other message passing framework is portability and speed. It has been implemented for almost every distributed memory architecture and each implementation is in principle optimized for the hardware on which it runs." }, { "code": null, "e": 28146, "s": 27939, "text": "Even though there are options available for multiple languages, Python is the most preferred one due to simplicity, ease of writing the code. So, now, we will now look at how to install MPI on ubuntu 14.10." }, { "code": null, "e": 28168, "s": 28146, "text": "Install MPI on Ubuntu" }, { "code": null, "e": 28300, "s": 28168, "text": "1) Step No. 1: Copy the following line of code in your terminal to install NumPy, a package for all scientific computing in python." }, { "code": null, "e": 28334, "s": 28300, "text": "sudo apt-get install python-numpy" }, { "code": null, "e": 28465, "s": 28334, "text": "2) After successful completion of the above step, execute the following commands to update the system and install the pip package." }, { "code": null, "e": 28574, "s": 28465, "text": " sudo apt-get update\n sudo apt-get -y install python-pip" }, { "code": null, "e": 28642, "s": 28574, "text": "3) Now, we will download the doc for the latest version of the MPI." }, { "code": null, "e": 28691, "s": 28642, "text": "sudo apt-get install libcr-dev mpich2 mpich2-doc" }, { "code": null, "e": 28749, "s": 28691, "text": "4) Enter the command to download MPI using pip for python" }, { "code": null, "e": 28773, "s": 28749, "text": "sudo pip install mpi4py" }, { "code": null, "e": 28808, "s": 28773, "text": "MPI is successfully installed now." }, { "code": null, "e": 28990, "s": 28808, "text": "Sometimes, a problem might pop up while clearing up the packages after MPI has been installed due to absence of dev tools in python. Yo can install them using the following command:" }, { "code": null, "e": 29022, "s": 28990, "text": "sudo apt-get install python-dev" }, { "code": null, "e": 29043, "s": 29024, "text": "MPI on Windows/MAC" }, { "code": null, "e": 29152, "s": 29043, "text": "For Windows/MAC user, they can visit the following link and download the .zip file and unzip and execute it:" }, { "code": null, "e": 29166, "s": 29152, "text": "MPI framework" }, { "code": null, "e": 29176, "s": 29166, "text": "Tutorials" }, { "code": null, "e": 29273, "s": 29176, "text": "Following installation, you can refer to the following documentation for using MPI using python." }, { "code": null, "e": 29324, "s": 29273, "text": "https://mpi4py.scipy.org/docs/usrman/tutorial.html" }, { "code": null, "e": 29335, "s": 29324, "text": "References" }, { "code": null, "e": 29361, "s": 29335, "text": "https://www.open-mpi.org/" }, { "code": null, "e": 29417, "s": 29361, "text": "https://en.wikipedia.org/wiki/Message_Passing_Interface" }, { "code": null, "e": 29609, "s": 29417, "text": "About the Author: Anurag Mishra currently a 3rd year B.Tech student is an avid software follower and a full stack web developer. His keen interest lies in web development, NLP and networking." }, { "code": null, "e": 29712, "s": 29609, "text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks." }, { "code": null, "e": 29719, "s": 29712, "text": "srinam" }, { "code": null, "e": 29725, "s": 29719, "text": "GBlog" }, { "code": null, "e": 29823, "s": 29725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29832, "s": 29823, "text": "Comments" }, { "code": null, "e": 29845, "s": 29832, "text": "Old Comments" }, { "code": null, "e": 29887, "s": 29845, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29912, "s": 29887, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 29956, "s": 29912, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29988, "s": 29956, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 30041, "s": 29988, "text": "Top 10 System Design Interview Questions and Answers" }, { "code": null, "e": 30078, "s": 30041, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 30100, "s": 30078, "text": "XML parsing in Python" }, { "code": null, "e": 30133, "s": 30100, "text": "Working with PDF files in Python" }, { "code": null, "e": 30152, "s": 30133, "text": "Genetic Algorithms" } ]
I want to resize and position a JFrame in Java. How can I achieve that?
To resize and position JFrame, use the Dimensions class. Here, we have set the bounds for the frame − int width = 500; int height = 400; Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); frame.setBounds((int) size.getWidth() - width, 0, width, height); The following is an example to resize and poisiton a frame − package my; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Register!"); JLabel label1, label2, label3; frame.setLayout(new GridLayout(2, 2)); label1 = new JLabel("Id", SwingConstants.CENTER); label2 = new JLabel("Age", SwingConstants.CENTER); label3 = new JLabel("Password", SwingConstants.CENTER); JTextField emailId = new JTextField(20); JTextField age = new JTextField(20); JPasswordField passwd = new JPasswordField(); passwd.setEchoChar('*'); frame.add(label1); frame.add(label2); frame.add(label3); frame.add(emailId); frame.add(age); frame.add(passwd); int width = 500; int height = 400; Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); frame.setBounds((int) size.getWidth() - width, 0, width, height); frame.setVisible(true); } }
[ { "code": null, "e": 1164, "s": 1062, "text": "To resize and position JFrame, use the Dimensions class. Here, we have set the bounds for the frame −" }, { "code": null, "e": 1327, "s": 1164, "text": "int width = 500;\nint height = 400;\nDimension size = Toolkit.getDefaultToolkit().getScreenSize();\nframe.setBounds((int) size.getWidth() - width, 0, width, height);" }, { "code": null, "e": 1388, "s": 1327, "text": "The following is an example to resize and poisiton a frame −" }, { "code": null, "e": 2620, "s": 1388, "text": "package my;\nimport java.awt.Dimension;\nimport java.awt.GridLayout;\nimport java.awt.Toolkit;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame.setDefaultLookAndFeelDecorated(true);\n JFrame frame = new JFrame(\"Register!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"Id\", SwingConstants.CENTER);\n label2 = new JLabel(\"Age\", SwingConstants.CENTER);\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n JTextField emailId = new JTextField(20);\n JTextField age = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(emailId);\n frame.add(age);\n frame.add(passwd);\n int width = 500;\n int height = 400;\n Dimension size = Toolkit.getDefaultToolkit().getScreenSize();\n frame.setBounds((int) size.getWidth() - width, 0, width, height);\n frame.setVisible(true);\n }\n}" } ]
Tryit Editor v3.7
Tryit: HTML aside element
[]
JavaScript Tutorial
JavaScript is the world's most popular programming language. JavaScript is the programming language of the Web. JavaScript is easy to learn. This tutorial will teach you JavaScript from basic to advanced. With our "Try it Yourself" editor, you can edit the source code and view the result. Try it Yourself » We recommend reading this tutorial, in the sequence listed in the menu. If you have a large screen, the menu will always be present on the left. If you have a small screen, open the menu by clicking the top menu sign ☰. Examples are better than 1000 words. Examples are often easier to understand than text explanations. This tutorial supplements all explanations with clarifying "Try it Yourself" examples. If you try all the examples, you will learn a lot about JavaScript, in a very short time! JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages This tutorial covers every version of JavaScript: The Original JavaScript ES1 ES2 ES3 (1997-1999) The First Main Revision ES5 (2009) The Second Revision ES6 (2015) The Yearly Additions (2016, 2017, 2018) In this tutorial, the learning speed is your choice. Everything is up to you. If you are struggling, take a break, or re-read the material. Always make sure you understand all the "Try-it-Yourself" examples. The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code ! Create a variable called carName and assign the value Volvo to it. var = ""; Start the Exercise How do I get JavaScript? Where can I download JavaScript? Is JavaScript Free? You don't have to get or download JavaScript. JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone. JavaScript is free to use for everyone. W3Schools maintains a complete JavaScript reference, including all HTML and browser objects. The reference contains examples for all properties, methods and events, and is continuously updated according to the latest web standards. Test your JavaScript skills at W3Schools! Start JavaScript Quiz! Get certified by completing the JavaScript course 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: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 61, "s": 0, "text": "JavaScript is the world's most popular programming language." }, { "code": null, "e": 112, "s": 61, "text": "JavaScript is the programming language of the Web." }, { "code": null, "e": 141, "s": 112, "text": "JavaScript is easy to learn." }, { "code": null, "e": 205, "s": 141, "text": "This tutorial will teach you JavaScript from basic to advanced." }, { "code": null, "e": 291, "s": 205, "text": "With our \"Try it Yourself\" editor, you can edit the source code and view \nthe result." }, { "code": null, "e": 311, "s": 291, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 383, "s": 311, "text": "We recommend reading this tutorial, in the sequence listed in the menu." }, { "code": null, "e": 456, "s": 383, "text": "If you have a large screen, the menu will always be present on the left." }, { "code": null, "e": 531, "s": 456, "text": "If you have a small screen, open the menu by clicking the top menu sign ☰." }, { "code": null, "e": 633, "s": 531, "text": "Examples are better than 1000 words. Examples are often easier to understand \nthan text explanations." }, { "code": null, "e": 720, "s": 633, "text": "This tutorial supplements all explanations with clarifying \"Try it Yourself\" examples." }, { "code": null, "e": 810, "s": 720, "text": "If you try all the examples, you will learn a lot about JavaScript, in a very short time!" }, { "code": null, "e": 880, "s": 810, "text": "JavaScript is one of the 3 languages all web developers \nmust \nlearn:" }, { "code": null, "e": 926, "s": 880, "text": " 1. HTML to define the content of web pages" }, { "code": null, "e": 971, "s": 926, "text": " 2. CSS to specify the layout of web pages" }, { "code": null, "e": 1026, "s": 971, "text": " 3. JavaScript to program the behavior of web pages " }, { "code": null, "e": 1076, "s": 1026, "text": "This tutorial covers every version of JavaScript:" }, { "code": null, "e": 1124, "s": 1076, "text": "The Original JavaScript ES1 ES2 ES3 (1997-1999)" }, { "code": null, "e": 1159, "s": 1124, "text": "The First Main Revision ES5 (2009)" }, { "code": null, "e": 1190, "s": 1159, "text": "The Second Revision ES6 (2015)" }, { "code": null, "e": 1230, "s": 1190, "text": "The Yearly Additions (2016, 2017, 2018)" }, { "code": null, "e": 1283, "s": 1230, "text": "In this tutorial, the learning speed is your choice." }, { "code": null, "e": 1308, "s": 1283, "text": "Everything is up to you." }, { "code": null, "e": 1370, "s": 1308, "text": "If you are struggling, take a break, or re-read the material." }, { "code": null, "e": 1439, "s": 1370, "text": "Always make sure you understand all the \"Try-it-Yourself\" \nexamples." }, { "code": null, "e": 1538, "s": 1439, "text": "The only way to become a clever programmer is to:\nPractice. Practice. Practice. Code. Code. Code !" }, { "code": null, "e": 1605, "s": 1538, "text": "Create a variable called carName and assign the value Volvo to it." }, { "code": null, "e": 1617, "s": 1605, "text": "var = \"\";\n" }, { "code": null, "e": 1636, "s": 1617, "text": "Start the Exercise" }, { "code": null, "e": 1661, "s": 1636, "text": "How do I get JavaScript?" }, { "code": null, "e": 1694, "s": 1661, "text": "Where can I download JavaScript?" }, { "code": null, "e": 1714, "s": 1694, "text": "Is JavaScript Free?" }, { "code": null, "e": 1760, "s": 1714, "text": "You don't have to get or download JavaScript." }, { "code": null, "e": 1865, "s": 1760, "text": "JavaScript is already running in your browser on your computer,\non your tablet, and on your smart-phone." }, { "code": null, "e": 1905, "s": 1865, "text": "JavaScript is free to use for everyone." }, { "code": null, "e": 1998, "s": 1905, "text": "W3Schools maintains a complete JavaScript reference, including all HTML and browser objects." }, { "code": null, "e": 2138, "s": 1998, "text": "The reference contains examples for all properties, methods and events, and \nis continuously updated according to the latest web standards." }, { "code": null, "e": 2180, "s": 2138, "text": "Test your JavaScript skills at W3Schools!" }, { "code": null, "e": 2203, "s": 2180, "text": "Start JavaScript Quiz!" }, { "code": null, "e": 2253, "s": 2203, "text": "Get certified by completing the JavaScript course" }, { "code": null, "e": 2286, "s": 2253, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2328, "s": 2286, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2435, "s": 2328, "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": 2454, "s": 2435, "text": "help@w3schools.com" } ]
Difference between readObject and readResolve method in serialization
Serialization is the process of converting object to stream byte and storing byte stream in database or memory. Class which implements java.io.Serializable interface can be serialized. Class which is implementing this interface gives the responsibility to JVM for serialize or persist java object As per the oracle docs − readObject method − Each subclass of a serializable object may define its own readObject method. If a class does not implement the method, the default serialization provided by defaultReadObject will be used. When implemented, the class is only responsible for restoring its own fields, not those of its supertypes or subtypes.The readObject method of the class, if implemented, is responsible for restoring the state of the class. The values of every field of the object whether transient or not, static or not are set to the default value for the fields type. The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered. 1 Basic The readObject method is used to deserialize an object from the stream The readResolve method is called when objectInputStream has read an object from the stream and is preparing to return it to the caller 2 Class It is part of ObjectInputStream class It is part of ObjectInputStream 3 It does not check the construction of object The readResolve method is not invoked on the object until the object is fully constructed import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Main { public static void main(String[] args) { User object = new User(1, "Ram"); String filename = "tutorialPoints.ser"; User object1 = null; try { // Reading the object from a file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); object1 = (User) in.readObject(); in.close(); file.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } } } class User implements java.io.Serializable { public int id; public String name; // Default constructor public User(int id, String name) { this.id = id; this.name = name; } }
[ { "code": null, "e": 1248, "s": 1062, "text": "Serialization is the process of converting object to stream byte and storing byte stream in database or memory. Class which implements java.io.Serializable interface can be serialized. " }, { "code": null, "e": 1361, "s": 1248, "text": "Class which is implementing this interface gives the responsibility to JVM for serialize or persist java object " }, { "code": null, "e": 1386, "s": 1361, "text": "As per the oracle docs −" }, { "code": null, "e": 1948, "s": 1386, "text": "readObject method − Each subclass of a serializable object may define its own readObject method. If a class does not implement the method, the default serialization provided by defaultReadObject will be used. When implemented, the class is only responsible for restoring its own fields, not those of its supertypes or subtypes.The readObject method of the class, if implemented, is responsible for restoring the state of the class. The values of every field of the object whether transient or not, static or not are set to the default value for the fields type." }, { "code": null, "e": 2479, "s": 1948, "text": "The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered." }, { "code": null, "e": 2481, "s": 2479, "text": "1" }, { "code": null, "e": 2488, "s": 2481, "text": "Basic " }, { "code": null, "e": 2559, "s": 2488, "text": "The readObject method is used to deserialize an object from the stream" }, { "code": null, "e": 2694, "s": 2559, "text": "The readResolve method is called when objectInputStream has read an object from the stream and is preparing to return it to the caller" }, { "code": null, "e": 2696, "s": 2694, "text": "2" }, { "code": null, "e": 2703, "s": 2696, "text": "Class " }, { "code": null, "e": 2742, "s": 2703, "text": "It is part of ObjectInputStream class " }, { "code": null, "e": 2775, "s": 2742, "text": "It is part of ObjectInputStream " }, { "code": null, "e": 2777, "s": 2775, "text": "3" }, { "code": null, "e": 2823, "s": 2777, "text": "It does not check the construction of object " }, { "code": null, "e": 2913, "s": 2823, "text": "The readResolve method is not invoked on the object until the object is fully constructed" }, { "code": null, "e": 3885, "s": 2913, "text": "import java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\npublic class Main {\n public static void main(String[] args) {\n User object = new User(1, \"Ram\");\n String filename = \"tutorialPoints.ser\";\n User object1 = null;\n try {\n // Reading the object from a file\n FileInputStream file = new FileInputStream(filename);\n ObjectInputStream in = new ObjectInputStream(file);\n object1 = (User) in.readObject();\n in.close();\n file.close();\n }\n catch (IOException ex) {\n ex.printStackTrace();\n }\n catch (ClassNotFoundException ex) {\n ex.printStackTrace();\n }\n }\n}\nclass User implements java.io.Serializable {\n public int id;\n public String name;\n // Default constructor\n public User(int id, String name) {\n this.id = id;\n this.name = name;\n }\n}" } ]
ReactJS defaultProps - GeeksforGeeks
26 Mar, 2021 The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class. 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. Creating defaultProps in class-based component: Now write down the following code in the App.js file. Here, App is our default component where we have written our code using a class-based component. App.js import React, { Component } from 'react'; class App extends Component { render() { return ( <div > <Person name="kapil" eyeColor="blue" age="23"></Person> <Person name="Sachin" eyeColor="blue" ></Person> <Person name="Nikhil" age="23"></Person> <Person eyeColor="green" age="23"></Person> </div> ); }} class Person extends Component { render() { return ( <div> <p> Name: {this.props.name} </p> <p>EyeColor: {this.props.eyeColor}</p> <p>Age : {this.props.age} </p> </div> ) }} Person.defaultProps = { name: "Rahul", eyeColor: "deepblue", age: "45"} 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: Creating defaultProps in Functional Component: Now write down the following code in the App.js file. Here, App is our default component where we have written our code using a functional component. App.js import React from 'react'; function App(props) { return ( <div > <Person name="kapil" eyeColor="blue" age="23"></Person> <Person name="Sachin" eyeColor="blue" ></Person> <Person name="Nikhil" age="23"></Person> <Person eyeColor="green" age="23"></Person> </div> );} function Person(props) { return ( <div> <p> Name: {props.name} </p> <p>EyeColor: {props.eyeColor}</p> <p>Age : {props.age} </p> <hr></hr> </div> )} Person.defaultProps = { name: "Rahul", eyeColor: "deepblue", age: "45"} 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: Picked ReactJS-Basics ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Re-rendering Components in ReactJS How to set background images in ReactJS ? ReactJS useCallback Hook How to create a table in ReactJS ? How to navigate on path by button click in react router ? 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 insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24037, "s": 24009, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24315, "s": 24037, "text": "The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class." }, { "code": null, "e": 24379, "s": 24315, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 24411, "s": 24379, "text": "npx create-react-app foldername" }, { "code": null, "e": 24511, "s": 24411, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 24525, "s": 24511, "text": "cd foldername" }, { "code": null, "e": 24577, "s": 24525, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 24776, "s": 24577, "text": "Creating defaultProps in class-based component: Now write down the following code in the App.js file. Here, App is our default component where we have written our code using a class-based component." }, { "code": null, "e": 24783, "s": 24776, "text": "App.js" }, { "code": "import React, { Component } from 'react'; class App extends Component { render() { return ( <div > <Person name=\"kapil\" eyeColor=\"blue\" age=\"23\"></Person> <Person name=\"Sachin\" eyeColor=\"blue\" ></Person> <Person name=\"Nikhil\" age=\"23\"></Person> <Person eyeColor=\"green\" age=\"23\"></Person> </div> ); }} class Person extends Component { render() { return ( <div> <p> Name: {this.props.name} </p> <p>EyeColor: {this.props.eyeColor}</p> <p>Age : {this.props.age} </p> </div> ) }} Person.defaultProps = { name: \"Rahul\", eyeColor: \"deepblue\", age: \"45\"} export default App;", "e": 25443, "s": 24783, "text": null }, { "code": null, "e": 25556, "s": 25443, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 25566, "s": 25556, "text": "npm start" }, { "code": null, "e": 25665, "s": 25566, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 25862, "s": 25665, "text": "Creating defaultProps in Functional Component: Now write down the following code in the App.js file. Here, App is our default component where we have written our code using a functional component." }, { "code": null, "e": 25869, "s": 25862, "text": "App.js" }, { "code": "import React from 'react'; function App(props) { return ( <div > <Person name=\"kapil\" eyeColor=\"blue\" age=\"23\"></Person> <Person name=\"Sachin\" eyeColor=\"blue\" ></Person> <Person name=\"Nikhil\" age=\"23\"></Person> <Person eyeColor=\"green\" age=\"23\"></Person> </div> );} function Person(props) { return ( <div> <p> Name: {props.name} </p> <p>EyeColor: {props.eyeColor}</p> <p>Age : {props.age} </p> <hr></hr> </div> )} Person.defaultProps = { name: \"Rahul\", eyeColor: \"deepblue\", age: \"45\"} export default App;", "e": 26438, "s": 25869, "text": null }, { "code": null, "e": 26551, "s": 26438, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26561, "s": 26551, "text": "npm start" }, { "code": null, "e": 26660, "s": 26561, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 26667, "s": 26660, "text": "Picked" }, { "code": null, "e": 26682, "s": 26667, "text": "ReactJS-Basics" }, { "code": null, "e": 26690, "s": 26682, "text": "ReactJS" }, { "code": null, "e": 26707, "s": 26690, "text": "Web Technologies" }, { "code": null, "e": 26805, "s": 26707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26814, "s": 26805, "text": "Comments" }, { "code": null, "e": 26827, "s": 26814, "text": "Old Comments" }, { "code": null, "e": 26862, "s": 26827, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 26904, "s": 26862, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 26929, "s": 26904, "text": "ReactJS useCallback Hook" }, { "code": null, "e": 26964, "s": 26929, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27022, "s": 26964, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27078, "s": 27022, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27111, "s": 27078, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27173, "s": 27111, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27223, "s": 27173, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Power BI - Timeseries, Aggregation, and Filters - GeeksforGeeks
18 Sep, 2020 Prerequisite: Power BI – Drilling Down and Up in Hierarchies This article discusses the various important concepts of Power BI along with its implementation. The following concepts will be discussed here : Time SeriesAggregationFilters Time Series Aggregation Filters Understanding the Dataset:The dataset used is of ‘Long-Term-Unemployment-Stats’. Refer to the dataset to follow along with the below given sections of the article – Dataset The data is formatted in such a way that with each row we can find the number of Unemployed people of a particular Age group and Gender in present in a particular Period. (Refer to the image of dataset given below.) The structure of the dataset is focused on efficiency in machine understanding rather than human beings. Snapshot of Dataset used Creating a Line Chart:To understand the concept of Time Series, we need to create a line chart for our data in Power BI. Steps Involved: Step 1 - Upload your dataset. Step 2 - Drag and Drop 'Period' and 'Unemployed' from Fields. Step 3 - Click on your graph and select Line Chart from the visualization panel. Power BI : Line Chart For every year, we have a separate point representing the number of unemployed people in that year. Each data point represent the aggregate or sum of all unemployed people in that particular year. Time Series:Time Series forecasting is a technique used in machine learning, which analyzes data and the sequence of time to predict future events. It is the collection of data at regular intervals in terms of Days, Hours, Months, and Years. We will implement Time Series using 2 approaches : Approach 1: Using Show next level drilling.In this approach, we do not treat the data as a continuous set of points, we treat them as categorical variables.We take the average of unemployment across different quarters of the year, not the sum.Show next level is used when we are looking at averages of the time series data to gain valuable information. Steps Involved: Step 1 - Click on your line chart. Go to values section and right click on 'Unemployed' and select Average. (Doing this will convert your line chart from sum to average as shown in Fig 1) Step 2 - Go to 'Switch to next level' and press it to drill data points to lower level. Example : Average of Unemployed by [Year --> Quarter --> Month] (Shown in Fig 2) Fig 1 : Conversion from sum to avg of unemployed ( STEP 1 ) Fig 2 : Switch to next level ( STEP 2 ) Here, we observe that following things in the given Time Series: 1. The average unemployment in the third quarter was the highest. 2. The average unemployment in the months of June and July are the lowest. Approach 2 : Using Expand to next level drilling.In this approach, we treat the data as a contiguous set of points. (not categorical variables). The data points increases as we drill down to the next level. In a way, it transforms into continuous time-series data. Steps Involved: Step 1 - Convert your 'unemployed' column back to sum from average. Step 2 - Step 2 - Go to 'Expand all down one level' and press it to drill data points to lower level. Example: Unemployed by [Year --> Quarter --> Month] (Shown in Fig 3) Fig 3 : Expand all down one level ( STEP 2 ) Aggregation and Granularity:When you combine values in your data, it’s called Aggregating. The result of that mathematical operation is an aggregate. We use sum, average, min/max etc for aggregating values in the data. On the contrary, Granularity is the segregation of data points. When we increase the rate of aggregation, the rate of granularity decreases. Steps Involved: Step 1 - Go to 'Expand all down one level' and press it to drill data points to the month level. (Shown in Fig 4) Step 2 - Put values like 'Gender' and 'Age' into the legend tab one by one. (Shown in Fig 5) Using the legends shown above the line chart, observe as the granularity of data increases. Fig 4 : Expand all from [Year] –> [Year,Quarter and Month] ( STEP 1 ) Fig 5 : Adding Legends to Line Chart ( STEP 2 ) Stacked Area Chart:Before understanding the concept of Filters and Slicer, we need to create a stacked area chart. Steps Involved: Step 1 - Select the line chart 'Unemployed by Year, Quarter, Month and Age'. (Shown in Fig 5) Step 2 - Go to visualization panel and select 'Stacked Area Chart'. (Shown in Fig 6) Fig 6 : Power BI : Stacked Area Chart Filters:Filters in Power BI are used to sort data and information based on certain selected criteria. Using it, we can extract specific information from our data. For example, we have the stock market data of 5 companies for a week. Using filters, we can choose a particular company and a particular date for which we want to show the data. Steps Involved: Step 1 - Select your Stacked Area Chart Visualization created above. Step 2 - Drag and Drop 'Gender' column into Filter Pane as shown in Fig 7. Step 3 - Now you can select between Male and Female or both, for the section of the data you want to display. Fig 7 : Power BI : Filtering Slicers:Slicers in Power BI are ‘on canvas visual filters‘. The slicers, like filters, enable a user to filter the data and view the desired information. Unlike filters, the slicers are present as a visual on the report and let a user select values as they are analyzing the report. Multiple slicers can be created on one page. (As shown in Fig 8) Steps Involved: Step 1 - Unselect any visualization. (if selected) Step 2 - Select 'Slicer' from visualization panel. You will se a blank panel appear in the Report View. Step 3 - Select specific data segments from 'Gender' and 'Age' slicer to get the filtered data as shown in Fig 8. Fig 8 : Power BI : Slicers These were some of the important concepts one must be aware of while making reports involving large business intelligence decisions. These tools help make very informative and user-friendly reports. They are extensively used by businesses in many real-world applications. For any doubt/queries, drop a comment below. Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Principal Component Analysis with Python Python | Decision Tree Regression using sklearn Python | Stemming words with NLTK Normalization vs Standardization Intuition of Adam Optimizer
[ { "code": null, "e": 23953, "s": 23925, "text": "\n18 Sep, 2020" }, { "code": null, "e": 24014, "s": 23953, "text": "Prerequisite: Power BI – Drilling Down and Up in Hierarchies" }, { "code": null, "e": 24159, "s": 24014, "text": "This article discusses the various important concepts of Power BI along with its implementation. The following concepts will be discussed here :" }, { "code": null, "e": 24189, "s": 24159, "text": "Time SeriesAggregationFilters" }, { "code": null, "e": 24201, "s": 24189, "text": "Time Series" }, { "code": null, "e": 24213, "s": 24201, "text": "Aggregation" }, { "code": null, "e": 24221, "s": 24213, "text": "Filters" }, { "code": null, "e": 24394, "s": 24221, "text": "Understanding the Dataset:The dataset used is of ‘Long-Term-Unemployment-Stats’. Refer to the dataset to follow along with the below given sections of the article – Dataset" }, { "code": null, "e": 24715, "s": 24394, "text": "The data is formatted in such a way that with each row we can find the number of Unemployed people of a particular Age group and Gender in present in a particular Period. (Refer to the image of dataset given below.) The structure of the dataset is focused on efficiency in machine understanding rather than human beings." }, { "code": null, "e": 24740, "s": 24715, "text": "Snapshot of Dataset used" }, { "code": null, "e": 24861, "s": 24740, "text": "Creating a Line Chart:To understand the concept of Time Series, we need to create a line chart for our data in Power BI." }, { "code": null, "e": 25055, "s": 24861, "text": "Steps Involved: \n\nStep 1 - Upload your dataset.\nStep 2 - Drag and Drop 'Period' and 'Unemployed' from Fields.\nStep 3 - Click on your graph and select Line Chart from the visualization panel. \n\n" }, { "code": null, "e": 25077, "s": 25055, "text": "Power BI : Line Chart" }, { "code": null, "e": 25177, "s": 25077, "text": "For every year, we have a separate point representing the number of unemployed people in that year." }, { "code": null, "e": 25274, "s": 25177, "text": "Each data point represent the aggregate or sum of all unemployed people in that particular year." }, { "code": null, "e": 25516, "s": 25274, "text": "Time Series:Time Series forecasting is a technique used in machine learning, which analyzes data and the sequence of time to predict future events. It is the collection of data at regular intervals in terms of Days, Hours, Months, and Years." }, { "code": null, "e": 25567, "s": 25516, "text": "We will implement Time Series using 2 approaches :" }, { "code": null, "e": 25920, "s": 25567, "text": "Approach 1: Using Show next level drilling.In this approach, we do not treat the data as a continuous set of points, we treat them as categorical variables.We take the average of unemployment across different quarters of the year, not the sum.Show next level is used when we are looking at averages of the time series data to gain valuable information." }, { "code": null, "e": 26299, "s": 25920, "text": "Steps Involved: \n\nStep 1 - Click on your line chart. Go to values section and right click on 'Unemployed' and select Average.\n(Doing this will convert your line chart from sum to average as shown in Fig 1)\n\nStep 2 - Go to 'Switch to next level' and press it to drill data points to lower level. \nExample : Average of Unemployed by [Year --> Quarter --> Month] (Shown in Fig 2)\n\n" }, { "code": null, "e": 26359, "s": 26299, "text": "Fig 1 : Conversion from sum to avg of unemployed ( STEP 1 )" }, { "code": null, "e": 26399, "s": 26359, "text": "Fig 2 : Switch to next level ( STEP 2 )" }, { "code": null, "e": 26608, "s": 26399, "text": "Here, we observe that following things in the given Time Series:\n\n1. The average unemployment in the third quarter was the highest.\n2. The average unemployment in the months of June and July are the lowest.\n\n" }, { "code": null, "e": 26873, "s": 26608, "text": "Approach 2 : Using Expand to next level drilling.In this approach, we treat the data as a contiguous set of points. (not categorical variables). The data points increases as we drill down to the next level. In a way, it transforms into continuous time-series data." }, { "code": null, "e": 27135, "s": 26873, "text": "Steps Involved: \n\nStep 1 - Convert your 'unemployed' column back to sum from average. \n\nStep 2 - Step 2 - Go to 'Expand all down one level' and press it to drill data points to lower level. \nExample: Unemployed by [Year --> Quarter --> Month] (Shown in Fig 3)\n\n" }, { "code": null, "e": 27180, "s": 27135, "text": "Fig 3 : Expand all down one level ( STEP 2 )" }, { "code": null, "e": 27540, "s": 27180, "text": "Aggregation and Granularity:When you combine values in your data, it’s called Aggregating. The result of that mathematical operation is an aggregate. We use sum, average, min/max etc for aggregating values in the data. On the contrary, Granularity is the segregation of data points. When we increase the rate of aggregation, the rate of granularity decreases." }, { "code": null, "e": 27860, "s": 27540, "text": "Steps Involved:\n\nStep 1 - Go to 'Expand all down one level' and press it to drill data points to the month level. (Shown in Fig 4)\nStep 2 - Put values like 'Gender' and 'Age' into the legend tab one by one. (Shown in Fig 5)\n\nUsing the legends shown above the line chart, observe as the granularity of data increases. \n\n" }, { "code": null, "e": 27930, "s": 27860, "text": "Fig 4 : Expand all from [Year] –> [Year,Quarter and Month] ( STEP 1 )" }, { "code": null, "e": 27978, "s": 27930, "text": "Fig 5 : Adding Legends to Line Chart ( STEP 2 )" }, { "code": null, "e": 28093, "s": 27978, "text": "Stacked Area Chart:Before understanding the concept of Filters and Slicer, we need to create a stacked area chart." }, { "code": null, "e": 28293, "s": 28093, "text": "Steps Involved: \n\nStep 1 - Select the line chart 'Unemployed by Year, Quarter, Month and Age'. (Shown in Fig 5)\nStep 2 - Go to visualization panel and select 'Stacked Area Chart'. (Shown in Fig 6) \n\n" }, { "code": null, "e": 28331, "s": 28293, "text": "Fig 6 : Power BI : Stacked Area Chart" }, { "code": null, "e": 28672, "s": 28331, "text": "Filters:Filters in Power BI are used to sort data and information based on certain selected criteria. Using it, we can extract specific information from our data. For example, we have the stock market data of 5 companies for a week. Using filters, we can choose a particular company and a particular date for which we want to show the data." }, { "code": null, "e": 28946, "s": 28672, "text": "Steps Involved: \n\nStep 1 - Select your Stacked Area Chart Visualization created above.\nStep 2 - Drag and Drop 'Gender' column into Filter Pane as shown in Fig 7.\nStep 3 - Now you can select between Male and Female or both, for the section of the data you want to display.\n\n" }, { "code": null, "e": 28975, "s": 28946, "text": "Fig 7 : Power BI : Filtering" }, { "code": null, "e": 29323, "s": 28975, "text": "Slicers:Slicers in Power BI are ‘on canvas visual filters‘. The slicers, like filters, enable a user to filter the data and view the desired information. Unlike filters, the slicers are present as a visual on the report and let a user select values as they are analyzing the report. Multiple slicers can be created on one page. (As shown in Fig 8)" }, { "code": null, "e": 29614, "s": 29323, "text": "Steps Involved:\n\nStep 1 - Unselect any visualization. (if selected)\nStep 2 - Select 'Slicer' from visualization panel. You will se a blank panel appear in the Report View. \nStep 3 - Select specific data segments from 'Gender' and 'Age' slicer to get the filtered data as shown in Fig 8. \n\n" }, { "code": null, "e": 29641, "s": 29614, "text": "Fig 8 : Power BI : Slicers" }, { "code": null, "e": 29958, "s": 29641, "text": "These were some of the important concepts one must be aware of while making reports involving large business intelligence decisions. These tools help make very informative and user-friendly reports. They are extensively used by businesses in many real-world applications. For any doubt/queries, drop a comment below." }, { "code": null, "e": 30156, "s": 29958, "text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready." }, { "code": null, "e": 30173, "s": 30156, "text": "Machine Learning" }, { "code": null, "e": 30190, "s": 30173, "text": "Machine Learning" }, { "code": null, "e": 30288, "s": 30190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30297, "s": 30288, "text": "Comments" }, { "code": null, "e": 30310, "s": 30297, "text": "Old Comments" }, { "code": null, "e": 30366, "s": 30310, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 30408, "s": 30366, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 30441, "s": 30408, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 30469, "s": 30441, "text": "Types of Environments in AI" }, { "code": null, "e": 30508, "s": 30469, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 30549, "s": 30508, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 30597, "s": 30549, "text": "Python | Decision Tree Regression using sklearn" }, { "code": null, "e": 30631, "s": 30597, "text": "Python | Stemming words with NLTK" }, { "code": null, "e": 30664, "s": 30631, "text": "Normalization vs Standardization" } ]
Convert byte[] array to File using Java
18 May, 2022 As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java // Java Program to convert Byte Array to File // Importing required classesimport java.io.File;import java.io.FileOutputStream;import java.io.OutputStream; // Main classpublic class GFG { // Path of a file static String FILEPATH = ""; static File file = new File(FILEPATH); // Method 1 // To write the bytes into a file static void writeByte(byte[] bytes) { // Try block to check for exceptions try { // Initialize a pointer in file // using OutputStream OutputStream os = new FileOutputStream(file); // Starting writing the bytes in it os.write(bytes); // Display message onconsole for successful // execution System.out.println("Successfully" + " byte inserted"); // Close the file connections os.close(); } // Catch block to handle the exceptions catch (Exception e) { // Display exception on console System.out.println("Exception: " + e); } } // Method 2 // Main driver method public static void main(String args[]) { // Input string String string = "GeeksForGeeks" + " - A Computer Science" + " Portal for geeks"; // Getting byte array from string // using getBytes() method byte[] bytes = string.getBytes(); // Calling Method 1 to // convert byte array to file writeByte(bytes); }} Output: On console Successfully byte inserted Now let us also discuss the use-case in order how to write Integer, Double, Character Values in the File (using Wrapper Class) Example: Java // Java Program to Convert Integer, Character and Double// Types into Bytes and Writing it in a File // Importing required classesimport java.io.File;import java.io.FileOutputStream;import java.io.OutputStream; // Main classpublic class GFG { // Path of a file static String FILEPATH = ""; // Getting the file via creating File class object static File file = new File(FILEPATH); // Method 1 // Writing the bytes into a file static void writeByte(byte[] byteInt, byte[] byteChar, byte[] byteDouble) { // Try block to check for exceptions try { // Initialize a pointer in file // using OutputStream class object OutputStream os = new FileOutputStream(file); // Starting writing the bytes in it // Writing int value os.write(byteInt); // Writing char value os.write(byteChar); // Writing double value os.write(byteDouble); // Display message for successful execution of // program System.out.println( "Successfully byte inserted"); // Close the file connections // using close() method os.close(); } // Catch block to handle exceptions catch (Exception e) { // Display message when exceptions occurs System.out.println("Exception: " + e); } } // Method 2 // Main driver method public static void main(String args[]) { // Declaring and initializing data types int num = 56; char ch = 's'; double dec = 78.9; // Inserting integer value byte[] byteInt = Integer.toString(num).getBytes(); // Inserting character value byte[] byteChar = Character.toString(ch).getBytes(); // Inserting double value byte[] byteDouble = Double.toString(dec).getBytes(); // Calling Method 1 to // write the bytes into a file writeByte(byteInt, byteChar, byteDouble); }} Output: On console Successfully byte inserted solankimayank sagartomar9927 sweetyty rkbhola5 Java-Array-Programs Java-Arrays Java-Byte Picked Technical Scripter 2018 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 May, 2022" }, { "code": null, "e": 315, "s": 28, "text": "As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class." }, { "code": null, "e": 390, "s": 315, "text": "Implementation: Convert a String into a byte array and write it in a file." }, { "code": null, "e": 399, "s": 390, "text": "Example:" }, { "code": null, "e": 404, "s": 399, "text": "Java" }, { "code": "// Java Program to convert Byte Array to File // Importing required classesimport java.io.File;import java.io.FileOutputStream;import java.io.OutputStream; // Main classpublic class GFG { // Path of a file static String FILEPATH = \"\"; static File file = new File(FILEPATH); // Method 1 // To write the bytes into a file static void writeByte(byte[] bytes) { // Try block to check for exceptions try { // Initialize a pointer in file // using OutputStream OutputStream os = new FileOutputStream(file); // Starting writing the bytes in it os.write(bytes); // Display message onconsole for successful // execution System.out.println(\"Successfully\" + \" byte inserted\"); // Close the file connections os.close(); } // Catch block to handle the exceptions catch (Exception e) { // Display exception on console System.out.println(\"Exception: \" + e); } } // Method 2 // Main driver method public static void main(String args[]) { // Input string String string = \"GeeksForGeeks\" + \" - A Computer Science\" + \" Portal for geeks\"; // Getting byte array from string // using getBytes() method byte[] bytes = string.getBytes(); // Calling Method 1 to // convert byte array to file writeByte(bytes); }}", "e": 1950, "s": 404, "text": null }, { "code": null, "e": 1970, "s": 1950, "text": "Output: On console " }, { "code": null, "e": 1997, "s": 1970, "text": "Successfully byte inserted" }, { "code": null, "e": 2124, "s": 1997, "text": "Now let us also discuss the use-case in order how to write Integer, Double, Character Values in the File (using Wrapper Class)" }, { "code": null, "e": 2133, "s": 2124, "text": "Example:" }, { "code": null, "e": 2138, "s": 2133, "text": "Java" }, { "code": "// Java Program to Convert Integer, Character and Double// Types into Bytes and Writing it in a File // Importing required classesimport java.io.File;import java.io.FileOutputStream;import java.io.OutputStream; // Main classpublic class GFG { // Path of a file static String FILEPATH = \"\"; // Getting the file via creating File class object static File file = new File(FILEPATH); // Method 1 // Writing the bytes into a file static void writeByte(byte[] byteInt, byte[] byteChar, byte[] byteDouble) { // Try block to check for exceptions try { // Initialize a pointer in file // using OutputStream class object OutputStream os = new FileOutputStream(file); // Starting writing the bytes in it // Writing int value os.write(byteInt); // Writing char value os.write(byteChar); // Writing double value os.write(byteDouble); // Display message for successful execution of // program System.out.println( \"Successfully byte inserted\"); // Close the file connections // using close() method os.close(); } // Catch block to handle exceptions catch (Exception e) { // Display message when exceptions occurs System.out.println(\"Exception: \" + e); } } // Method 2 // Main driver method public static void main(String args[]) { // Declaring and initializing data types int num = 56; char ch = 's'; double dec = 78.9; // Inserting integer value byte[] byteInt = Integer.toString(num).getBytes(); // Inserting character value byte[] byteChar = Character.toString(ch).getBytes(); // Inserting double value byte[] byteDouble = Double.toString(dec).getBytes(); // Calling Method 1 to // write the bytes into a file writeByte(byteInt, byteChar, byteDouble); }}", "e": 4213, "s": 2138, "text": null }, { "code": null, "e": 4233, "s": 4213, "text": "Output: On console " }, { "code": null, "e": 4261, "s": 4233, "text": "Successfully byte inserted " }, { "code": null, "e": 4275, "s": 4261, "text": "solankimayank" }, { "code": null, "e": 4290, "s": 4275, "text": "sagartomar9927" }, { "code": null, "e": 4299, "s": 4290, "text": "sweetyty" }, { "code": null, "e": 4308, "s": 4299, "text": "rkbhola5" }, { "code": null, "e": 4328, "s": 4308, "text": "Java-Array-Programs" }, { "code": null, "e": 4340, "s": 4328, "text": "Java-Arrays" }, { "code": null, "e": 4350, "s": 4340, "text": "Java-Byte" }, { "code": null, "e": 4357, "s": 4350, "text": "Picked" }, { "code": null, "e": 4381, "s": 4357, "text": "Technical Scripter 2018" }, { "code": null, "e": 4386, "s": 4381, "text": "Java" }, { "code": null, "e": 4405, "s": 4386, "text": "Technical Scripter" }, { "code": null, "e": 4410, "s": 4405, "text": "Java" } ]
Largest Sum Contiguous Subarray
05 Jul, 2022 Write an efficient program to find the sum of the contiguous subarray within a one-dimensional array of numbers that has the largest sum. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Kadane’s Algorithm: Initialize: max_so_far = INT_MIN max_ending_here = 0 Loop for each element of the array (a) max_ending_here = max_ending_here + a[i] (b) if(max_so_far < max_ending_here) max_so_far = max_ending_here (c) if(max_ending_here < 0) max_ending_here = 0 return max_so_far Explanation: The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of the maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far Lets take the example: {-2, -3, 4, -1, -2, 1, 5, -3} max_so_far = INT_MIN max_ending_here = 0 for i=0, a[0] = -2 max_ending_here = max_ending_here + (-2) Set max_ending_here = 0 because max_ending_here < 0 and set max_so_far = -2 for i=1, a[1] = -3 max_ending_here = max_ending_here + (-3) Since max_ending_here = -3 and max_so_far = -2, max_so_far will remain -2 Set max_ending_here = 0 because max_ending_here < 0 for i=2, a[2] = 4 max_ending_here = max_ending_here + (4) max_ending_here = 4 max_so_far is updated to 4 because max_ending_here greater than max_so_far which was -2 till now for i=3, a[3] = -1 max_ending_here = max_ending_here + (-1) max_ending_here = 3 for i=4, a[4] = -2 max_ending_here = max_ending_here + (-2) max_ending_here = 1 for i=5, a[5] = 1 max_ending_here = max_ending_here + (1) max_ending_here = 2 for i=6, a[6] = 5 max_ending_here = max_ending_here + (5) max_ending_here = 7 max_so_far is updated to 7 because max_ending_here is greater than max_so_far for i=7, a[7] = -3 max_ending_here = max_ending_here + (-3) max_ending_here = 4 Note: The above algorithm only works if and only if at least one positive number should be present otherwise it does not work i.e if an Array contains all negative numbers it doesn’t work. Program: C++ Java Python C# PHP Javascript // C++ program to print largest contiguous array sum#include<iostream>#include<climits>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far;} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0;} import java.io.*;// Java program to print largest contiguous array sumimport java.util.*; class Kadane{ public static void main (String[] args) { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; System.out.println("Maximum contiguous sum is " + maxSubArraySum(a)); } static int maxSubArraySum(int a[]) { int size = a.length; int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; }} # Python program to find maximum contiguous subarray # Function to find the maximum contiguous subarrayfrom sys import maxintdef maxSubArraySum(a,size): max_so_far = -maxint - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far # Driver function to check the above function a = [-2, -3, 4, -1, -2, 1, 5, -3] print "Maximum contiguous sum is", maxSubArraySum(a,len(a)) #This code is contributed by _Devesh Agrawal_ // C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a) { int size = a.Length; int max_so_far = int.MinValue, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver code public static void Main () { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; Console.Write("Maximum contiguous sum is " + maxSubArraySum(a)); } } // This code is contributed by Sam007_ <?php// PHP program to print largest// contiguous array sum function maxSubArraySum($a, $size){ $max_so_far = PHP_INT_MIN; $max_ending_here = 0; for ($i = 0; $i < $size; $i++) { $max_ending_here = $max_ending_here + $a[$i]; if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here; if ($max_ending_here < 0) $max_ending_here = 0; } return $max_so_far;} // Driver code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = count($a);$max_sum = maxSubArraySum($a, $n);echo "Maximum contiguous sum is " , $max_sum; // This code is contributed by anuj_67.?> <script> // JavaScript program to find maximum // contiguous subarray // Function to find the maximum // contiguous subarrayfunction maxSubArraySum(a, size){ var maxint = Math.pow(2, 53) var max_so_far = -maxint - 1 var max_ending_here = 0 for (var i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here) max_so_far = max_ending_here if (max_ending_here < 0) max_ending_here = 0 } return max_so_far} // Driver codevar a = [ -2, -3, 4, -1, -2, 1, 5, -3 ]document.write("Maximum contiguous sum is", maxSubArraySum(a, a.length)) // This code is contributed by AnkThon </script> Maximum contiguous sum is 7 Time Complexity: O(n)Auxiliary Space: O(1) Another approach: C++ Java Python C# PHP Javascript int maxSubarraySum(int arr[], int size){ int max_ending_here = 0, max_so_far = INT_MIN; for (int i = 0; i < size; i++) { // include current element to previous subarray only // when it can add to a bigger number than itself. if (arr[i] <= max_ending_here + arr[i]) { max_ending_here += arr[i]; } // Else start the max subarray from current element else { max_ending_here = arr[i]; } if (max_ending_here > max_so_far) max_so_far = max_ending_here; } return max_so_far;} // contributed by Vipul Raj static int maxSubArraySum(int a[],int size) { int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // This code is contributed by ANKITRAI1 def maxSubArraySum(a,size): max_so_far = a[0] max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far static int maxSubArraySum(int[] a, int size){ int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // This code is contributed// by ChitraNayal <?php function maxSubArraySum(&$a, $size){$max_so_far = $a[0];$max_ending_here = 0;for ($i = 0; $i < $size; $i++){ $max_ending_here = $max_ending_here + $a[$i]; if ($max_ending_here < 0) $max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here;}return $max_so_far; // This code is contributed// by ChitraNayal?> <script> // JavaScript Program to implement // the above approach function maxSubarraySum(arr, size) { let max_ending_here = 0, max_so_far = Number.MIN_VALUE; for (let i = 0; i < size; i++) { // include current element to previous subarray only // when it can add to a bigger number than itself. if (arr[i] <= max_ending_here + arr[i]) { max_ending_here += arr[i]; } // Else start the max subarray from current element else { max_ending_here = arr[i]; } if (max_ending_here > max_so_far) { max_so_far = max_ending_here; } } return max_so_far; } // This code is contributed by Potta Lokesh </script> Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative. C++ Java Python C# PHP Javascript #include<iostream>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = max(a[i], curr_max+a[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far;} /* Driver program to test maxSubArraySum */int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0;} // Java program to print largest contiguous// array sumimport java.io.*; class GFG { static int maxSubArraySum(int a[], int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.max(a[i], curr_max+a[i]); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far; } /* Driver program to test maxSubArraySum */ public static void main(String[] args) { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.length; int max_sum = maxSubArraySum(a, n); System.out.println("Maximum contiguous sum is " + max_sum); }} // This code is contributed by Prerna Saini # Python program to find maximum contiguous subarray def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far # Driver function to check the above function a = [-2, -3, 4, -1, -2, 1, 5, -3]print"Maximum contiguous sum is" , maxSubArraySum(a,len(a)) #This code is contributed by _Devesh Agrawal_ // C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a, int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.Max(a[i], curr_max+a[i]); max_so_far = Math.Max(max_so_far, curr_max); } return max_so_far; } // Driver code public static void Main () { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write("Maximum contiguous sum is " + maxSubArraySum(a, n)); } } // This code is contributed by Sam007_ <?phpfunction maxSubArraySum($a, $size){ $max_so_far = $a[0]; $curr_max = $a[0]; for ($i = 1; $i < $size; $i++) { $curr_max = max($a[$i], $curr_max + $a[$i]); $max_so_far = max($max_so_far, $curr_max); } return $max_so_far;} // Driver Code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = sizeof($a);$max_sum = maxSubArraySum($a, $n);echo "Maximum contiguous sum is " . $max_sum; // This code is contributed // by Akanksha Rai(Abby_akku)?> <script>// C# program to print largest // contiguous array sum function maxSubArraySum(a,size){ let max_so_far = a[0]; let curr_max = a[0]; for (let i = 1; i < size; i++) { curr_max = Math.max(a[i], curr_max+a[i]); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far;} // Driver code let a = [-2, -3, 4, -1, -2, 1, 5, -3];let n = a.length; document.write("Maximum contiguous sum is ",maxSubArraySum(a, n)); </script> Maximum contiguous sum is 7 Time complexity: O(n), where n is the size of the array.Auxiliary Space: O(1) To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum. C++ Java Python3 C# PHP Javascript // C++ program to print largest contiguous array sum#include<iostream>#include<climits>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } cout << "Maximum contiguous sum is " << max_so_far << endl; cout << "Starting index "<< start << endl << "Ending index "<< end << endl;} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); return 0;} // Java program to print largest // contiguous array sumclass GFG { static void maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } System.out.println("Maximum contiguous sum is " + max_so_far); System.out.println("Starting index " + start); System.out.println("Ending index " + end); } // Driver code public static void main(String[] args) { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = a.length; maxSubArraySum(a, n); }} // This code is contributed by prerna saini # Python program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 print ("Maximum contiguous sum is %d"%(max_so_far)) print ("Starting Index %d"%(start)) print ("Ending Index %d"%(end)) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]maxSubArraySum(a,len(a)) // C# program to print largest // contiguous array sumusing System; class GFG { static void maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } Console.WriteLine("Maximum contiguous " + "sum is " + max_so_far); Console.WriteLine("Starting index " + start); Console.WriteLine("Ending index " + end); } // Driver code public static void Main() { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; maxSubArraySum(a, n); }} // This code is contributed// by anuj_67. <?php // PHP program to print largest // contiguous array sum function maxSubArraySum($a, $size){ $max_so_far = PHP_INT_MIN; $max_ending_here = 0; $start = 0; $end = 0; $s = 0; for ($i = 0; $i < $size; $i++) { $max_ending_here += $a[$i]; if ($max_so_far < $max_ending_here) { $max_so_far = $max_ending_here; $start = $s; $end = $i; } if ($max_ending_here < 0) { $max_ending_here = 0; $s = $i + 1; } } echo "Maximum contiguous sum is ". $max_so_far."\n"; echo "Starting index ". $start . "\n". "Ending index " . $end . "\n";} // Driver Code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = sizeof($a);$max_sum = maxSubArraySum($a, $n); // This code is contributed// by ChitraNayal?> <script>// javascript program to print largest // contiguous array sum function maxSubArraySum(a , size) { var max_so_far = Number.MIN_VALUE, max_ending_here = 0, start = 0, end = 0, s = 0; for (i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } document.write("Maximum contiguous sum is " + max_so_far); document.write("<br/>Starting index " + start); document.write("<br/>Ending index " + end); } // Driver code var a = [ -2, -3, 4, -1, -2, 1, 5, -3 ]; var n = a.length; maxSubArraySum(a, n); // This code is contributed by Rajput-Ji </script> Maximum contiguous sum is 7 Starting index 2 Ending index 6 Kadane’s Algorithm can be viewed both as greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with the previous sum OR restart a new range. Both choices are being taken care of in the implementation.Time Complexity: O(n)Auxiliary Space: O(1) Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying ‘n’ consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. vt_m ankthon Akanksha_Rai ukasp ankurchaudhary627 subhammahato348 vipul995 mohit kumar 29 surinderdawra388 Rajput-Ji lokeshpotta20 as5853535 misrapratyush20080 surindertarika1234 simmytarika5 nguyenhoangtam pranjaypoddar parthsahu95 o1613051 tarakki100 akashish__ 24*7 Innovation Labs Accolite Amazon Amazon-Question D-E-Shaw FactSet Flipkart Hike Housing.com MakeMyTrip MetLife Microsoft Morgan Stanley Ola Cabs Oracle OYO Rooms Payu Samsung Snapdeal subarray subarray-sum Teradata Visa Visa-Question VMWare Walmart Zoho Arrays Dynamic Programming VMWare Zoho Flipkart Morgan Stanley Accolite Amazon Microsoft OYO Rooms Samsung Snapdeal 24*7 Innovation Labs D-E-Shaw FactSet Hike Housing.com MakeMyTrip MetLife Ola Cabs Oracle Payu Teradata Visa Walmart Arrays Dynamic Programming 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, 2022" }, { "code": null, "e": 193, "s": 54, "text": "Write an efficient program to find the sum of the contiguous subarray within a one-dimensional array of numbers that has the largest sum. " }, { "code": null, "e": 204, "s": 195, "text": "Chapters" }, { "code": null, "e": 231, "s": 204, "text": "descriptions off, selected" }, { "code": null, "e": 281, "s": 231, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 304, "s": 281, "text": "captions off, selected" }, { "code": null, "e": 312, "s": 304, "text": "English" }, { "code": null, "e": 336, "s": 312, "text": "This is a modal window." }, { "code": null, "e": 405, "s": 336, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 427, "s": 405, "text": "End of dialog window." }, { "code": null, "e": 447, "s": 427, "text": "Kadane’s Algorithm:" }, { "code": null, "e": 751, "s": 447, "text": "Initialize:\n max_so_far = INT_MIN\n max_ending_here = 0\n\nLoop for each element of the array\n (a) max_ending_here = max_ending_here + a[i]\n (b) if(max_so_far < max_ending_here)\n max_so_far = max_ending_here\n (c) if(max_ending_here < 0)\n max_ending_here = 0\nreturn max_so_far" }, { "code": null, "e": 1126, "s": 751, "text": "Explanation: The simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array (max_ending_here is used for this). And keep track of the maximum sum contiguous segment among all positive segments (max_so_far is used for this). Each time we get a positive-sum compare it with max_so_far and update max_so_far if it is greater than max_so_far " }, { "code": null, "e": 2365, "s": 1126, "text": " Lets take the example:\n {-2, -3, 4, -1, -2, 1, 5, -3}\n\n max_so_far = INT_MIN\n max_ending_here = 0\n\n for i=0, a[0] = -2\n max_ending_here = max_ending_here + (-2)\n Set max_ending_here = 0 because max_ending_here < 0\n and set max_so_far = -2\n\n for i=1, a[1] = -3\n max_ending_here = max_ending_here + (-3)\n Since max_ending_here = -3 and max_so_far = -2, max_so_far will remain -2\n Set max_ending_here = 0 because max_ending_here < 0\n \n \n for i=2, a[2] = 4\n max_ending_here = max_ending_here + (4)\n max_ending_here = 4\n max_so_far is updated to 4 because max_ending_here greater \n than max_so_far which was -2 till now\n\n for i=3, a[3] = -1\n max_ending_here = max_ending_here + (-1)\n max_ending_here = 3\n\n for i=4, a[4] = -2\n max_ending_here = max_ending_here + (-2)\n max_ending_here = 1\n\n for i=5, a[5] = 1\n max_ending_here = max_ending_here + (1)\n max_ending_here = 2\n\n for i=6, a[6] = 5\n max_ending_here = max_ending_here + (5)\n max_ending_here = 7\n max_so_far is updated to 7 because max_ending_here is \n greater than max_so_far\n\n for i=7, a[7] = -3\n max_ending_here = max_ending_here + (-3)\n max_ending_here = 4" }, { "code": null, "e": 2554, "s": 2365, "text": "Note: The above algorithm only works if and only if at least one positive number should be present otherwise it does not work i.e if an Array contains all negative numbers it doesn’t work." }, { "code": null, "e": 2564, "s": 2554, "text": "Program: " }, { "code": null, "e": 2568, "s": 2564, "text": "C++" }, { "code": null, "e": 2573, "s": 2568, "text": "Java" }, { "code": null, "e": 2580, "s": 2573, "text": "Python" }, { "code": null, "e": 2583, "s": 2580, "text": "C#" }, { "code": null, "e": 2587, "s": 2583, "text": "PHP" }, { "code": null, "e": 2598, "s": 2587, "text": "Javascript" }, { "code": "// C++ program to print largest contiguous array sum#include<iostream>#include<climits>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far;} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << \"Maximum contiguous sum is \" << max_sum; return 0;}", "e": 3300, "s": 2598, "text": null }, { "code": "import java.io.*;// Java program to print largest contiguous array sumimport java.util.*; class Kadane{ public static void main (String[] args) { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; System.out.println(\"Maximum contiguous sum is \" + maxSubArraySum(a)); } static int maxSubArraySum(int a[]) { int size = a.length; int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; }}", "e": 4064, "s": 3300, "text": null }, { "code": "# Python program to find maximum contiguous subarray # Function to find the maximum contiguous subarrayfrom sys import maxintdef maxSubArraySum(a,size): max_so_far = -maxint - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far # Driver function to check the above function a = [-2, -3, 4, -1, -2, 1, 5, -3] print \"Maximum contiguous sum is\", maxSubArraySum(a,len(a)) #This code is contributed by _Devesh Agrawal_", "e": 4723, "s": 4064, "text": null }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a) { int size = a.Length; int max_so_far = int.MinValue, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver code public static void Main () { int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; Console.Write(\"Maximum contiguous sum is \" + maxSubArraySum(a)); } } // This code is contributed by Sam007_", "e": 5547, "s": 4723, "text": null }, { "code": "<?php// PHP program to print largest// contiguous array sum function maxSubArraySum($a, $size){ $max_so_far = PHP_INT_MIN; $max_ending_here = 0; for ($i = 0; $i < $size; $i++) { $max_ending_here = $max_ending_here + $a[$i]; if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here; if ($max_ending_here < 0) $max_ending_here = 0; } return $max_so_far;} // Driver code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = count($a);$max_sum = maxSubArraySum($a, $n);echo \"Maximum contiguous sum is \" , $max_sum; // This code is contributed by anuj_67.?>", "e": 6206, "s": 5547, "text": null }, { "code": "<script> // JavaScript program to find maximum // contiguous subarray // Function to find the maximum // contiguous subarrayfunction maxSubArraySum(a, size){ var maxint = Math.pow(2, 53) var max_so_far = -maxint - 1 var max_ending_here = 0 for (var i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here) max_so_far = max_ending_here if (max_ending_here < 0) max_ending_here = 0 } return max_so_far} // Driver codevar a = [ -2, -3, 4, -1, -2, 1, 5, -3 ]document.write(\"Maximum contiguous sum is\", maxSubArraySum(a, a.length)) // This code is contributed by AnkThon </script>", "e": 6921, "s": 6206, "text": null }, { "code": null, "e": 6949, "s": 6921, "text": "Maximum contiguous sum is 7" }, { "code": null, "e": 6992, "s": 6949, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 7010, "s": 6992, "text": "Another approach:" }, { "code": null, "e": 7014, "s": 7010, "text": "C++" }, { "code": null, "e": 7019, "s": 7014, "text": "Java" }, { "code": null, "e": 7026, "s": 7019, "text": "Python" }, { "code": null, "e": 7029, "s": 7026, "text": "C#" }, { "code": null, "e": 7033, "s": 7029, "text": "PHP" }, { "code": null, "e": 7044, "s": 7033, "text": "Javascript" }, { "code": "int maxSubarraySum(int arr[], int size){ int max_ending_here = 0, max_so_far = INT_MIN; for (int i = 0; i < size; i++) { // include current element to previous subarray only // when it can add to a bigger number than itself. if (arr[i] <= max_ending_here + arr[i]) { max_ending_here += arr[i]; } // Else start the max subarray from current element else { max_ending_here = arr[i]; } if (max_ending_here > max_so_far) max_so_far = max_ending_here; } return max_so_far;} // contributed by Vipul Raj", "e": 7658, "s": 7044, "text": null }, { "code": "static int maxSubArraySum(int a[],int size) { int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // This code is contributed by ANKITRAI1", "e": 8204, "s": 7658, "text": null }, { "code": "def maxSubArraySum(a,size): max_so_far = a[0] max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if max_ending_here < 0: max_ending_here = 0 # Do not compare for all elements. Compare only # when max_ending_here > 0 elif (max_so_far < max_ending_here): max_so_far = max_ending_here return max_so_far", "e": 8648, "s": 8204, "text": null }, { "code": "static int maxSubArraySum(int[] a, int size){ int max_so_far = a[0], max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far;} // This code is contributed// by ChitraNayal", "e": 9153, "s": 8648, "text": null }, { "code": "<?php function maxSubArraySum(&$a, $size){$max_so_far = $a[0];$max_ending_here = 0;for ($i = 0; $i < $size; $i++){ $max_ending_here = $max_ending_here + $a[$i]; if ($max_ending_here < 0) $max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if ($max_so_far < $max_ending_here) $max_so_far = $max_ending_here;}return $max_so_far; // This code is contributed// by ChitraNayal?>", "e": 9615, "s": 9153, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach function maxSubarraySum(arr, size) { let max_ending_here = 0, max_so_far = Number.MIN_VALUE; for (let i = 0; i < size; i++) { // include current element to previous subarray only // when it can add to a bigger number than itself. if (arr[i] <= max_ending_here + arr[i]) { max_ending_here += arr[i]; } // Else start the max subarray from current element else { max_ending_here = arr[i]; } if (max_ending_here > max_so_far) { max_so_far = max_ending_here; } } return max_so_far; } // This code is contributed by Potta Lokesh </script>", "e": 10503, "s": 9615, "text": null }, { "code": null, "e": 10694, "s": 10503, "text": "Algorithmic Paradigm: Dynamic ProgrammingFollowing is another simple implementation suggested by Mohit Kumar. The implementation handles the case when all numbers in the array are negative. " }, { "code": null, "e": 10698, "s": 10694, "text": "C++" }, { "code": null, "e": 10703, "s": 10698, "text": "Java" }, { "code": null, "e": 10710, "s": 10703, "text": "Python" }, { "code": null, "e": 10713, "s": 10710, "text": "C#" }, { "code": null, "e": 10717, "s": 10713, "text": "PHP" }, { "code": null, "e": 10728, "s": 10717, "text": "Javascript" }, { "code": "#include<iostream>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = max(a[i], curr_max+a[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far;} /* Driver program to test maxSubArraySum */int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); cout << \"Maximum contiguous sum is \" << max_sum; return 0;}", "e": 11247, "s": 10728, "text": null }, { "code": "// Java program to print largest contiguous// array sumimport java.io.*; class GFG { static int maxSubArraySum(int a[], int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.max(a[i], curr_max+a[i]); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far; } /* Driver program to test maxSubArraySum */ public static void main(String[] args) { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.length; int max_sum = maxSubArraySum(a, n); System.out.println(\"Maximum contiguous sum is \" + max_sum); }} // This code is contributed by Prerna Saini", "e": 11955, "s": 11247, "text": null }, { "code": "# Python program to find maximum contiguous subarray def maxSubArraySum(a,size): max_so_far =a[0] curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far # Driver function to check the above function a = [-2, -3, 4, -1, -2, 1, 5, -3]print\"Maximum contiguous sum is\" , maxSubArraySum(a,len(a)) #This code is contributed by _Devesh Agrawal_", "e": 12423, "s": 11955, "text": null }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG{ static int maxSubArraySum(int []a, int size) { int max_so_far = a[0]; int curr_max = a[0]; for (int i = 1; i < size; i++) { curr_max = Math.Max(a[i], curr_max+a[i]); max_so_far = Math.Max(max_so_far, curr_max); } return max_so_far; } // Driver code public static void Main () { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write(\"Maximum contiguous sum is \" + maxSubArraySum(a, n)); } } // This code is contributed by Sam007_", "e": 13061, "s": 12423, "text": null }, { "code": "<?phpfunction maxSubArraySum($a, $size){ $max_so_far = $a[0]; $curr_max = $a[0]; for ($i = 1; $i < $size; $i++) { $curr_max = max($a[$i], $curr_max + $a[$i]); $max_so_far = max($max_so_far, $curr_max); } return $max_so_far;} // Driver Code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = sizeof($a);$max_sum = maxSubArraySum($a, $n);echo \"Maximum contiguous sum is \" . $max_sum; // This code is contributed // by Akanksha Rai(Abby_akku)?>", "e": 13622, "s": 13061, "text": null }, { "code": "<script>// C# program to print largest // contiguous array sum function maxSubArraySum(a,size){ let max_so_far = a[0]; let curr_max = a[0]; for (let i = 1; i < size; i++) { curr_max = Math.max(a[i], curr_max+a[i]); max_so_far = Math.max(max_so_far, curr_max); } return max_so_far;} // Driver code let a = [-2, -3, 4, -1, -2, 1, 5, -3];let n = a.length; document.write(\"Maximum contiguous sum is \",maxSubArraySum(a, n)); </script>", "e": 14079, "s": 13622, "text": null }, { "code": null, "e": 14107, "s": 14079, "text": "Maximum contiguous sum is 7" }, { "code": null, "e": 14185, "s": 14107, "text": "Time complexity: O(n), where n is the size of the array.Auxiliary Space: O(1)" }, { "code": null, "e": 14284, "s": 14185, "text": "To print the subarray with the maximum sum, we maintain indices whenever we get the maximum sum. " }, { "code": null, "e": 14288, "s": 14284, "text": "C++" }, { "code": null, "e": 14293, "s": 14288, "text": "Java" }, { "code": null, "e": 14301, "s": 14293, "text": "Python3" }, { "code": null, "e": 14304, "s": 14301, "text": "C#" }, { "code": null, "e": 14308, "s": 14304, "text": "PHP" }, { "code": null, "e": 14319, "s": 14308, "text": "Javascript" }, { "code": "// C++ program to print largest contiguous array sum#include<iostream>#include<climits>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } cout << \"Maximum contiguous sum is \" << max_so_far << endl; cout << \"Starting index \"<< start << endl << \"Ending index \"<< end << endl;} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); int max_sum = maxSubArraySum(a, n); return 0;}", "e": 15216, "s": 14319, "text": null }, { "code": "// Java program to print largest // contiguous array sumclass GFG { static void maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } System.out.println(\"Maximum contiguous sum is \" + max_so_far); System.out.println(\"Starting index \" + start); System.out.println(\"Ending index \" + end); } // Driver code public static void main(String[] args) { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = a.length; maxSubArraySum(a, n); }} // This code is contributed by prerna saini", "e": 16264, "s": 15216, "text": null }, { "code": "# Python program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 print (\"Maximum contiguous sum is %d\"%(max_so_far)) print (\"Starting Index %d\"%(start)) print (\"Ending Index %d\"%(end)) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]maxSubArraySum(a,len(a))", "e": 17044, "s": 16264, "text": null }, { "code": "// C# program to print largest // contiguous array sumusing System; class GFG { static void maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } Console.WriteLine(\"Maximum contiguous \" + \"sum is \" + max_so_far); Console.WriteLine(\"Starting index \" + start); Console.WriteLine(\"Ending index \" + end); } // Driver code public static void Main() { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; maxSubArraySum(a, n); }} // This code is contributed// by anuj_67.", "e": 18207, "s": 17044, "text": null }, { "code": "<?php // PHP program to print largest // contiguous array sum function maxSubArraySum($a, $size){ $max_so_far = PHP_INT_MIN; $max_ending_here = 0; $start = 0; $end = 0; $s = 0; for ($i = 0; $i < $size; $i++) { $max_ending_here += $a[$i]; if ($max_so_far < $max_ending_here) { $max_so_far = $max_ending_here; $start = $s; $end = $i; } if ($max_ending_here < 0) { $max_ending_here = 0; $s = $i + 1; } } echo \"Maximum contiguous sum is \". $max_so_far.\"\\n\"; echo \"Starting index \". $start . \"\\n\". \"Ending index \" . $end . \"\\n\";} // Driver Code$a = array(-2, -3, 4, -1, -2, 1, 5, -3);$n = sizeof($a);$max_sum = maxSubArraySum($a, $n); // This code is contributed// by ChitraNayal?>", "e": 19058, "s": 18207, "text": null }, { "code": "<script>// javascript program to print largest // contiguous array sum function maxSubArraySum(a , size) { var max_so_far = Number.MIN_VALUE, max_ending_here = 0, start = 0, end = 0, s = 0; for (i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } document.write(\"Maximum contiguous sum is \" + max_so_far); document.write(\"<br/>Starting index \" + start); document.write(\"<br/>Ending index \" + end); } // Driver code var a = [ -2, -3, 4, -1, -2, 1, 5, -3 ]; var n = a.length; maxSubArraySum(a, n); // This code is contributed by Rajput-Ji </script>", "e": 19970, "s": 19058, "text": null }, { "code": null, "e": 20031, "s": 19970, "text": "Maximum contiguous sum is 7\nStarting index 2\nEnding index 6\n" }, { "code": null, "e": 20567, "s": 20031, "text": "Kadane’s Algorithm can be viewed both as greedy and DP. As we can see that we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0 (Greedy Part). This is because continuing with a negative sum is way worse than restarting with a new range. Now it can also be viewed as a DP, at each stage we have 2 choices: Either take the current element and continue with the previous sum OR restart a new range. Both choices are being taken care of in the implementation.Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 20856, "s": 20567, "text": "Now try the below question Given an array of integers (possibly some elements negative), write a C program to find out the *maximum product* possible by multiplying ‘n’ consecutive integers in the array where n ≤ ARRAY_SIZE. Also, print the starting point of the maximum product subarray." }, { "code": null, "e": 20984, "s": 20856, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 20989, "s": 20984, "text": "vt_m" }, { "code": null, "e": 20997, "s": 20989, "text": "ankthon" }, { "code": null, "e": 21010, "s": 20997, "text": "Akanksha_Rai" }, { "code": null, "e": 21016, "s": 21010, "text": "ukasp" }, { "code": null, "e": 21034, "s": 21016, "text": "ankurchaudhary627" }, { "code": null, "e": 21050, "s": 21034, "text": "subhammahato348" }, { "code": null, "e": 21059, "s": 21050, "text": "vipul995" }, { "code": null, "e": 21074, "s": 21059, "text": "mohit kumar 29" }, { "code": null, "e": 21091, "s": 21074, "text": "surinderdawra388" }, { "code": null, "e": 21101, "s": 21091, "text": "Rajput-Ji" }, { "code": null, "e": 21115, "s": 21101, "text": "lokeshpotta20" }, { "code": null, "e": 21125, "s": 21115, "text": "as5853535" }, { "code": null, "e": 21144, "s": 21125, "text": "misrapratyush20080" }, { "code": null, "e": 21163, "s": 21144, "text": "surindertarika1234" }, { "code": null, "e": 21176, "s": 21163, "text": "simmytarika5" }, { "code": null, "e": 21191, "s": 21176, "text": "nguyenhoangtam" }, { "code": null, "e": 21205, "s": 21191, "text": "pranjaypoddar" }, { "code": null, "e": 21217, "s": 21205, "text": "parthsahu95" }, { "code": null, "e": 21226, "s": 21217, "text": "o1613051" }, { "code": null, "e": 21237, "s": 21226, "text": "tarakki100" }, { "code": null, "e": 21248, "s": 21237, "text": "akashish__" }, { "code": null, "e": 21269, "s": 21248, "text": "24*7 Innovation Labs" }, { "code": null, "e": 21278, "s": 21269, "text": "Accolite" }, { "code": null, "e": 21285, "s": 21278, "text": "Amazon" }, { "code": null, "e": 21301, "s": 21285, "text": "Amazon-Question" }, { "code": null, "e": 21310, "s": 21301, "text": "D-E-Shaw" }, { "code": null, "e": 21318, "s": 21310, "text": "FactSet" }, { "code": null, "e": 21327, "s": 21318, "text": "Flipkart" }, { "code": null, "e": 21332, "s": 21327, "text": "Hike" }, { "code": null, "e": 21344, "s": 21332, "text": "Housing.com" }, { "code": null, "e": 21355, "s": 21344, "text": "MakeMyTrip" }, { "code": null, "e": 21363, "s": 21355, "text": "MetLife" }, { "code": null, "e": 21373, "s": 21363, "text": "Microsoft" }, { "code": null, "e": 21388, "s": 21373, "text": "Morgan Stanley" }, { "code": null, "e": 21397, "s": 21388, "text": "Ola Cabs" }, { "code": null, "e": 21404, "s": 21397, "text": "Oracle" }, { "code": null, "e": 21414, "s": 21404, "text": "OYO Rooms" }, { "code": null, "e": 21419, "s": 21414, "text": "Payu" }, { "code": null, "e": 21427, "s": 21419, "text": "Samsung" }, { "code": null, "e": 21436, "s": 21427, "text": "Snapdeal" }, { "code": null, "e": 21445, "s": 21436, "text": "subarray" }, { "code": null, "e": 21458, "s": 21445, "text": "subarray-sum" }, { "code": null, "e": 21467, "s": 21458, "text": "Teradata" }, { "code": null, "e": 21472, "s": 21467, "text": "Visa" }, { "code": null, "e": 21486, "s": 21472, "text": "Visa-Question" }, { "code": null, "e": 21493, "s": 21486, "text": "VMWare" }, { "code": null, "e": 21501, "s": 21493, "text": "Walmart" }, { "code": null, "e": 21506, "s": 21501, "text": "Zoho" }, { "code": null, "e": 21513, "s": 21506, "text": "Arrays" }, { "code": null, "e": 21533, "s": 21513, "text": "Dynamic Programming" }, { "code": null, "e": 21540, "s": 21533, "text": "VMWare" }, { "code": null, "e": 21545, "s": 21540, "text": "Zoho" }, { "code": null, "e": 21554, "s": 21545, "text": "Flipkart" }, { "code": null, "e": 21569, "s": 21554, "text": "Morgan Stanley" }, { "code": null, "e": 21578, "s": 21569, "text": "Accolite" }, { "code": null, "e": 21585, "s": 21578, "text": "Amazon" }, { "code": null, "e": 21595, "s": 21585, "text": "Microsoft" }, { "code": null, "e": 21605, "s": 21595, "text": "OYO Rooms" }, { "code": null, "e": 21613, "s": 21605, "text": "Samsung" }, { "code": null, "e": 21622, "s": 21613, "text": "Snapdeal" }, { "code": null, "e": 21643, "s": 21622, "text": "24*7 Innovation Labs" }, { "code": null, "e": 21652, "s": 21643, "text": "D-E-Shaw" }, { "code": null, "e": 21660, "s": 21652, "text": "FactSet" }, { "code": null, "e": 21665, "s": 21660, "text": "Hike" }, { "code": null, "e": 21677, "s": 21665, "text": "Housing.com" }, { "code": null, "e": 21688, "s": 21677, "text": "MakeMyTrip" }, { "code": null, "e": 21696, "s": 21688, "text": "MetLife" }, { "code": null, "e": 21705, "s": 21696, "text": "Ola Cabs" }, { "code": null, "e": 21712, "s": 21705, "text": "Oracle" }, { "code": null, "e": 21717, "s": 21712, "text": "Payu" }, { "code": null, "e": 21726, "s": 21717, "text": "Teradata" }, { "code": null, "e": 21731, "s": 21726, "text": "Visa" }, { "code": null, "e": 21739, "s": 21731, "text": "Walmart" }, { "code": null, "e": 21746, "s": 21739, "text": "Arrays" }, { "code": null, "e": 21766, "s": 21746, "text": "Dynamic Programming" } ]
YearMonth format() method in Java
04 Sep, 2021 The format() method of YearMonth class in Java is used to format this YearMonth instance according to a specified DateTimeFormatter for year-month passed as parameter to this method. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a single parameter formatter which is the DateTimeFormatter according to which this YearMonth instance will be formatted.Return Value: It returns the value of this YearMonth as a string after formatting it according to the specified formatter.Below programs illustrate the format() method of YearMonth in Java: Program 1: Java // Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2017, 8); // Create a DateTimeFormatter string DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM"); // Format this year-month System.out.println(thisYearMonth.format(formatter)); }} 17/08 Program 2: Java // Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2018, 5); // Create a DateTimeFormatter string DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy"); // Format this year-month System.out.println(thisYearMonth.format(formatter)); }} 05/18 Reference: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#format-java.time.format.DateTimeFormatter- anikakapoor Java-Functions Java-time package Java-YearMonth Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2021" }, { "code": null, "e": 212, "s": 28, "text": "The format() method of YearMonth class in Java is used to format this YearMonth instance according to a specified DateTimeFormatter for year-month passed as parameter to this method. " }, { "code": null, "e": 221, "s": 212, "text": "Syntax: " }, { "code": null, "e": 271, "s": 221, "text": "public String format(DateTimeFormatter formatter)" }, { "code": null, "e": 626, "s": 271, "text": "Parameter: This method accepts a single parameter formatter which is the DateTimeFormatter according to which this YearMonth instance will be formatted.Return Value: It returns the value of this YearMonth as a string after formatting it according to the specified formatter.Below programs illustrate the format() method of YearMonth in Java: Program 1: " }, { "code": null, "e": 631, "s": 626, "text": "Java" }, { "code": "// Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2017, 8); // Create a DateTimeFormatter string DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yy/MM\"); // Format this year-month System.out.println(thisYearMonth.format(formatter)); }}", "e": 1136, "s": 631, "text": null }, { "code": null, "e": 1142, "s": 1136, "text": "17/08" }, { "code": null, "e": 1156, "s": 1144, "text": "Program 2: " }, { "code": null, "e": 1161, "s": 1156, "text": "Java" }, { "code": "// Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Create a YearMonth object YearMonth thisYearMonth = YearMonth.of(2018, 5); // Create a DateTimeFormatter string DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"MM/yy\"); // Format this year-month System.out.println(thisYearMonth.format(formatter)); }}", "e": 1666, "s": 1161, "text": null }, { "code": null, "e": 1672, "s": 1666, "text": "05/18" }, { "code": null, "e": 1795, "s": 1674, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#format-java.time.format.DateTimeFormatter-" }, { "code": null, "e": 1807, "s": 1795, "text": "anikakapoor" }, { "code": null, "e": 1822, "s": 1807, "text": "Java-Functions" }, { "code": null, "e": 1840, "s": 1822, "text": "Java-time package" }, { "code": null, "e": 1855, "s": 1840, "text": "Java-YearMonth" }, { "code": null, "e": 1860, "s": 1855, "text": "Java" }, { "code": null, "e": 1865, "s": 1860, "text": "Java" }, { "code": null, "e": 1963, "s": 1865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2014, "s": 1963, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2045, "s": 2014, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2064, "s": 2045, "text": "Interfaces in Java" }, { "code": null, "e": 2094, "s": 2064, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2112, "s": 2094, "text": "ArrayList in Java" }, { "code": null, "e": 2132, "s": 2112, "text": "Collections in Java" }, { "code": null, "e": 2147, "s": 2132, "text": "Stream In Java" }, { "code": null, "e": 2179, "s": 2147, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2203, "s": 2179, "text": "Singleton Class in Java" } ]
How to compare two NumPy arrays?
03 Jun, 2022 Here we will be focusing on the comparison done using NumPy on arrays. Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index is the same. Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray.all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent. Python3 import numpy as np an_array = np.array([[1, 2], [3, 4]])another_array = np.array([[1, 2], [3, 4]]) comparison = an_array == another_arrayequal_arrays = comparison.all() print(equal_arrays) Output: True Method 2: We can also use greater than, less than and equal to operators to compare. To understand, have a look at the code below. Syntax : numpy.greater(x1, x2[, out]) Syntax : numpy.greater_equal(x1, x2[, out]) Syntax : numpy.less(x1, x2[, out]) Syntax : numpy.less_equal(x1, x2[, out]) Python3 import numpy as np a = np.array([101, 99, 87])b = np.array([897, 97, 111]) print("Array a: ", a)print("Array b: ", b) print("a > b")print(np.greater(a, b)) print("a >= b")print(np.greater_equal(a, b)) print("a < b")print(np.less(a, b)) print("a <= b")print(np.less_equal(a, b)) Output: This array_equal() function checks if two arrays have the same elements and same shape. Syntax: numpy.array_equal(arr1, arr2) Parameters: arr1 : [array_like]Input array or object whose elements, we need to test. arr2 : [array_like]Input array or object whose elements, we need to test. Return Type: True, two arrays have the same elements and same shape.; otherwise False Example Python3 import numpy as np arr1 = np.array([[1, 2], [3, 4]])arr2 = np.array([[1, 2], [3, 4]]) # Comparing the arraysif np.array_equal(arr1, arr2): print("Equal")else: print("Not Equal") Output: Equal kothavvsaakash pulamolusaimohan Python numpy-arrayManipulation 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method 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": 53, "s": 25, "text": "\n03 Jun, 2022" }, { "code": null, "e": 261, "s": 53, "text": "Here we will be focusing on the comparison done using NumPy on arrays. Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index is the same. " }, { "code": null, "e": 476, "s": 261, "text": "Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray.all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent. " }, { "code": null, "e": 484, "s": 476, "text": "Python3" }, { "code": "import numpy as np an_array = np.array([[1, 2], [3, 4]])another_array = np.array([[1, 2], [3, 4]]) comparison = an_array == another_arrayequal_arrays = comparison.all() print(equal_arrays)", "e": 673, "s": 484, "text": null }, { "code": null, "e": 681, "s": 673, "text": "Output:" }, { "code": null, "e": 686, "s": 681, "text": "True" }, { "code": null, "e": 817, "s": 686, "text": "Method 2: We can also use greater than, less than and equal to operators to compare. To understand, have a look at the code below." }, { "code": null, "e": 975, "s": 817, "text": "Syntax : numpy.greater(x1, x2[, out])\nSyntax : numpy.greater_equal(x1, x2[, out])\nSyntax : numpy.less(x1, x2[, out])\nSyntax : numpy.less_equal(x1, x2[, out])" }, { "code": null, "e": 983, "s": 975, "text": "Python3" }, { "code": "import numpy as np a = np.array([101, 99, 87])b = np.array([897, 97, 111]) print(\"Array a: \", a)print(\"Array b: \", b) print(\"a > b\")print(np.greater(a, b)) print(\"a >= b\")print(np.greater_equal(a, b)) print(\"a < b\")print(np.less(a, b)) print(\"a <= b\")print(np.less_equal(a, b))", "e": 1262, "s": 983, "text": null }, { "code": null, "e": 1270, "s": 1262, "text": "Output:" }, { "code": null, "e": 1360, "s": 1272, "text": "This array_equal() function checks if two arrays have the same elements and same shape." }, { "code": null, "e": 1368, "s": 1360, "text": "Syntax:" }, { "code": null, "e": 1399, "s": 1368, "text": "numpy.array_equal(arr1, arr2) " }, { "code": null, "e": 1411, "s": 1399, "text": "Parameters:" }, { "code": null, "e": 1488, "s": 1411, "text": "arr1 : [array_like]Input array or object whose elements, we need to test." }, { "code": null, "e": 1565, "s": 1488, "text": "arr2 : [array_like]Input array or object whose elements, we need to test." }, { "code": null, "e": 1651, "s": 1565, "text": "Return Type: True, two arrays have the same elements and same shape.; otherwise False" }, { "code": null, "e": 1659, "s": 1651, "text": "Example" }, { "code": null, "e": 1667, "s": 1659, "text": "Python3" }, { "code": "import numpy as np arr1 = np.array([[1, 2], [3, 4]])arr2 = np.array([[1, 2], [3, 4]]) # Comparing the arraysif np.array_equal(arr1, arr2): print(\"Equal\")else: print(\"Not Equal\")", "e": 1852, "s": 1667, "text": null }, { "code": null, "e": 1860, "s": 1852, "text": "Output:" }, { "code": null, "e": 1866, "s": 1860, "text": "Equal" }, { "code": null, "e": 1881, "s": 1866, "text": "kothavvsaakash" }, { "code": null, "e": 1898, "s": 1881, "text": "pulamolusaimohan" }, { "code": null, "e": 1929, "s": 1898, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 1942, "s": 1929, "text": "Python-numpy" }, { "code": null, "e": 1949, "s": 1942, "text": "Python" }, { "code": null, "e": 2047, "s": 1949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2079, "s": 2047, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2106, "s": 2079, "text": "Python Classes and Objects" }, { "code": null, "e": 2127, "s": 2106, "text": "Python OOPs Concepts" }, { "code": null, "e": 2150, "s": 2127, "text": "Introduction To PYTHON" }, { "code": null, "e": 2181, "s": 2150, "text": "Python | os.path.join() method" }, { "code": null, "e": 2237, "s": 2181, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2279, "s": 2237, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2321, "s": 2279, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2360, "s": 2321, "text": "Python | Get unique values from a list" } ]
Lasso Regression in R Programming
28 Sep, 2021 Lasso regression is a classification algorithm that uses shrinkage in simple and sparse models(i.e model with fewer parameters). In Shrinkage, data values are shrunk towards a central point like the mean. Lasso regression is a regularized regression algorithm that performs L1 regularization which adds penalty equal to the absolute value of the magnitude of coefficients. “LASSO” stands for Least Absolute Shrinkage and Selection Operator. Lasso regression is good for models showing high levels of multicollinearity or when you want to automate certain parts of model selection i.e variable selection or parameter elimination. Lasso regression solutions are quadratic programming problems that can best solve with software like RStudio, Matlab, etc. It has the ability to select predictors. The algorithm minimizes the sum of squares with constraint. Some Beta are shrunk to zero that results in a regression model. A tuning parameter lambda controls the strength of the L1 regularization penalty. lambda is basically the amount of shrinkage: When lambda = 0, no parameters are eliminated. As lambda increases, more and more coefficients are set to zero and eliminated & bias increases. When lambda = infinity, all coefficients are eliminated. As lambda decreases, variance increases. Also, If an intercept is included in the model, it is left unchanged. Now let’s implementing Lasso regression in R programming. The Dataset Big Mart dataset consists of 1559 products across 10 stores in different cities. Certain attributes of each product and store have been defined. It consists of 12 features i.e Item_Identifier( is a unique product ID assigned to every distinct item), Item_Weight(includes the weight of the product), Item_Fat_Content(describes whether the product is low fat or not), Item_Visibility(mentions the percentage of the total display area of all products in a store allocated to the particular product), Item_Type(describes the food category to which the item belongs), Item_MRP(Maximum Retail Price (list price) of the product), Outlet_Identifier(unique store ID assigned. It consists of an alphanumeric string of length 6), Outlet_Establishment_Year(mentions the year in which store was established), Outlet_Size(tells the size of the store in terms of ground area covered), Outlet_Location_Type(tells about the size of the city in which the store is located), Outlet_Type(tells whether the outlet is just a grocery store or some sort of supermarket) and Item_Outlet_Sales( sales of the product in the particular store). R # Loading datatrain = fread("Train_UWu5bXk.csv")test = fread("Test_u94Q5KV.csv") # Structurestr(train) Output: Performing Lasso Regression on Dataset Using the Lasso regression algorithm on the dataset which includes 12 features with 1559 products across 10 stores in different cities. R # Installing Packagesinstall.packages("data.table")install.packages("dplyr")install.packages("glmnet")install.packages("ggplot2")install.packages("caret")install.packages("xgboost")install.packages("e1071")install.packages("cowplot") # load packageslibrary(data.table) # used for reading and manipulation of datalibrary(dplyr) # used for data manipulation and joininglibrary(glmnet) # used for regressionlibrary(ggplot2) # used for plotinglibrary(caret) # used for modelinglibrary(xgboost) # used for building XGBoost modellibrary(e1071) # used for skewnesslibrary(cowplot) # used for combining multiple plots # Loading datasetstrain = fread("Train_UWu5bXk.csv")test = fread("Test_u94Q5KV.csv") # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA] combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){ item = combi$Item_Identifier[i] combi$Item_Weight[i] = mean(combi$Item_Weight[combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){ item = combi$Item_Identifier[i] combi$Item_Visibility[i] = mean(combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == "Small", 0, ifelse(Outlet_Size == "Medium", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == "Tier 3", 0, ifelse(Outlet_Location_Type == "Tier 2", 1, 2))] combi[, c("Outlet_Size", "Outlet_Location_Type") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars("~.", data = combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c("Item_Identifier", "Outlet_Establishment_Year", "Item_Type")])) combi = cbind(combi[, "Item_Identifier"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility)skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering datanum_vars = which(sapply(combi, is.numeric)) # index of numeric featuresnum_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, "Item_Outlet_Sales"), with = F] prep_num = preProcess(combi_numeric, method=c("center", "scale"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, "Item_Outlet_Sales") := NULL]combi = cbind(combi, combi_numeric_norm) # splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building :Lasso Regressionset.seed(123)control = trainControl(method ="cv", number = 5)Grid_la_reg = expand.grid(alpha = 1, lambda = seq(0.001, 0.1, by = 0.0002)) # Training lasso regression modellasso_model = train(x = train[, -c("Item_Identifier", "Item_Outlet_Sales")], y = train$Item_Outlet_Sales, method = "glmnet", trControl = control, tuneGrid = Grid_reg )lasso_model # mean validation scoremean(lasso_model$resample$RMSE) # Plotplot(lasso_model, main = "Lasso Regression") Output: Model lasso_model: The Lasso regression model uses the alpha value as 1 and lambda value as 0.1. RMSE was used to select the optimal model using the smallest value. Mean validation score: The mean validation score of the model is 1128.869. Plot: The regularization parameter increases, RMSE remains constant. sumitgumber28 R Data-science R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Sep, 2021" }, { "code": null, "e": 401, "s": 28, "text": "Lasso regression is a classification algorithm that uses shrinkage in simple and sparse models(i.e model with fewer parameters). In Shrinkage, data values are shrunk towards a central point like the mean. Lasso regression is a regularized regression algorithm that performs L1 regularization which adds penalty equal to the absolute value of the magnitude of coefficients." }, { "code": null, "e": 822, "s": 401, "text": "“LASSO” stands for Least Absolute Shrinkage and Selection Operator. Lasso regression is good for models showing high levels of multicollinearity or when you want to automate certain parts of model selection i.e variable selection or parameter elimination. Lasso regression solutions are quadratic programming problems that can best solve with software like RStudio, Matlab, etc. It has the ability to select predictors. " }, { "code": null, "e": 1075, "s": 822, "text": "The algorithm minimizes the sum of squares with constraint. Some Beta are shrunk to zero that results in a regression model. A tuning parameter lambda controls the strength of the L1 regularization penalty. lambda is basically the amount of shrinkage: " }, { "code": null, "e": 1123, "s": 1075, "text": "When lambda = 0, no parameters are eliminated. " }, { "code": null, "e": 1221, "s": 1123, "text": "As lambda increases, more and more coefficients are set to zero and eliminated & bias increases. " }, { "code": null, "e": 1279, "s": 1221, "text": "When lambda = infinity, all coefficients are eliminated. " }, { "code": null, "e": 1321, "s": 1279, "text": "As lambda decreases, variance increases. " }, { "code": null, "e": 1449, "s": 1321, "text": "Also, If an intercept is included in the model, it is left unchanged. Now let’s implementing Lasso regression in R programming." }, { "code": null, "e": 1461, "s": 1449, "text": "The Dataset" }, { "code": null, "e": 2577, "s": 1461, "text": "Big Mart dataset consists of 1559 products across 10 stores in different cities. Certain attributes of each product and store have been defined. It consists of 12 features i.e Item_Identifier( is a unique product ID assigned to every distinct item), Item_Weight(includes the weight of the product), Item_Fat_Content(describes whether the product is low fat or not), Item_Visibility(mentions the percentage of the total display area of all products in a store allocated to the particular product), Item_Type(describes the food category to which the item belongs), Item_MRP(Maximum Retail Price (list price) of the product), Outlet_Identifier(unique store ID assigned. It consists of an alphanumeric string of length 6), Outlet_Establishment_Year(mentions the year in which store was established), Outlet_Size(tells the size of the store in terms of ground area covered), Outlet_Location_Type(tells about the size of the city in which the store is located), Outlet_Type(tells whether the outlet is just a grocery store or some sort of supermarket) and Item_Outlet_Sales( sales of the product in the particular store)." }, { "code": null, "e": 2579, "s": 2577, "text": "R" }, { "code": "# Loading datatrain = fread(\"Train_UWu5bXk.csv\")test = fread(\"Test_u94Q5KV.csv\") # Structurestr(train)", "e": 2684, "s": 2579, "text": null }, { "code": null, "e": 2693, "s": 2684, "text": "Output: " }, { "code": null, "e": 2732, "s": 2693, "text": "Performing Lasso Regression on Dataset" }, { "code": null, "e": 2868, "s": 2732, "text": "Using the Lasso regression algorithm on the dataset which includes 12 features with 1559 products across 10 stores in different cities." }, { "code": null, "e": 2870, "s": 2868, "text": "R" }, { "code": "# Installing Packagesinstall.packages(\"data.table\")install.packages(\"dplyr\")install.packages(\"glmnet\")install.packages(\"ggplot2\")install.packages(\"caret\")install.packages(\"xgboost\")install.packages(\"e1071\")install.packages(\"cowplot\") # load packageslibrary(data.table) # used for reading and manipulation of datalibrary(dplyr) # used for data manipulation and joininglibrary(glmnet) # used for regressionlibrary(ggplot2) # used for plotinglibrary(caret) # used for modelinglibrary(xgboost) # used for building XGBoost modellibrary(e1071) # used for skewnesslibrary(cowplot) # used for combining multiple plots # Loading datasetstrain = fread(\"Train_UWu5bXk.csv\")test = fread(\"Test_u94Q5KV.csv\") # Setting test dataset# Combining datasets# add Item_Outlet_Sales to test datatest[, Item_Outlet_Sales := NA] combi = rbind(train, test) # Missing Value Treatmentmissing_index = which(is.na(combi$Item_Weight))for(i in missing_index){ item = combi$Item_Identifier[i] combi$Item_Weight[i] = mean(combi$Item_Weight[combi$Item_Identifier == item], na.rm = T)} # Replacing 0 in Item_Visibility with meanzero_index = which(combi$Item_Visibility == 0)for(i in zero_index){ item = combi$Item_Identifier[i] combi$Item_Visibility[i] = mean(combi$Item_Visibility[combi$Item_Identifier == item], na.rm = T)} # Label Encoding# To convert categorical in numericalcombi[, Outlet_Size_num := ifelse(Outlet_Size == \"Small\", 0, ifelse(Outlet_Size == \"Medium\", 1, 2))] combi[, Outlet_Location_Type_num := ifelse(Outlet_Location_Type == \"Tier 3\", 0, ifelse(Outlet_Location_Type == \"Tier 2\", 1, 2))] combi[, c(\"Outlet_Size\", \"Outlet_Location_Type\") := NULL] # One Hot Encoding# To convert categorical in numericalohe_1 = dummyVars(\"~.\", data = combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")], fullRank = T)ohe_df = data.table(predict(ohe_1, combi[, -c(\"Item_Identifier\", \"Outlet_Establishment_Year\", \"Item_Type\")])) combi = cbind(combi[, \"Item_Identifier\"], ohe_df) # Remove skewnessskewness(combi$Item_Visibility)skewness(combi$price_per_unit_wt) # log + 1 to avoid division by zerocombi[, Item_Visibility := log(Item_Visibility + 1)] # Scaling and Centering datanum_vars = which(sapply(combi, is.numeric)) # index of numeric featuresnum_vars_names = names(num_vars) combi_numeric = combi[, setdiff(num_vars_names, \"Item_Outlet_Sales\"), with = F] prep_num = preProcess(combi_numeric, method=c(\"center\", \"scale\"))combi_numeric_norm = predict(prep_num, combi_numeric) # removing numeric independent variablescombi[, setdiff(num_vars_names, \"Item_Outlet_Sales\") := NULL]combi = cbind(combi, combi_numeric_norm) # splitting data back to train and testtrain = combi[1:nrow(train)]test = combi[(nrow(train) + 1):nrow(combi)] # Removing Item_Outlet_Salestest[, Item_Outlet_Sales := NULL] # Model Building :Lasso Regressionset.seed(123)control = trainControl(method =\"cv\", number = 5)Grid_la_reg = expand.grid(alpha = 1, lambda = seq(0.001, 0.1, by = 0.0002)) # Training lasso regression modellasso_model = train(x = train[, -c(\"Item_Identifier\", \"Item_Outlet_Sales\")], y = train$Item_Outlet_Sales, method = \"glmnet\", trControl = control, tuneGrid = Grid_reg )lasso_model # mean validation scoremean(lasso_model$resample$RMSE) # Plotplot(lasso_model, main = \"Lasso Regression\")", "e": 6791, "s": 2870, "text": null }, { "code": null, "e": 6800, "s": 6791, "text": "Output: " }, { "code": null, "e": 6820, "s": 6800, "text": "Model lasso_model: " }, { "code": null, "e": 6966, "s": 6820, "text": "The Lasso regression model uses the alpha value as 1 and lambda value as 0.1. RMSE was used to select the optimal model using the smallest value." }, { "code": null, "e": 6990, "s": 6966, "text": "Mean validation score: " }, { "code": null, "e": 7043, "s": 6990, "text": "The mean validation score of the model is 1128.869. " }, { "code": null, "e": 7050, "s": 7043, "text": "Plot: " }, { "code": null, "e": 7113, "s": 7050, "text": "The regularization parameter increases, RMSE remains constant." }, { "code": null, "e": 7127, "s": 7113, "text": "sumitgumber28" }, { "code": null, "e": 7142, "s": 7127, "text": "R Data-science" }, { "code": null, "e": 7161, "s": 7142, "text": "R Machine-Learning" }, { "code": null, "e": 7172, "s": 7161, "text": "R Language" } ]
Python3 – if , if..else, Nested if, if-elif statements
11 Apr, 2022 There comes situations in real life when we need to do some specific task and based on some specific conditions and, we decide what should we do next. Similarly there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditional statements provided by Python. if if..else Nested if if-elif statements. Let us go through all of them. If the simple code of block is to be performed if the condition holds true then if statement is used. Here the condition mentioned holds true then the code of block runs otherwise not. Syntax: if condition: # Statements to execute if # condition is true Flowchart:- Example: Python3 # if statement exampleif 10 > 5: print("10 greater than 5") print("Program ended") Output: 10 greater than 5 Program ended Indentation(White space) is used to delimit the block of code. As shown in the above example it is mandatory to use indentation in Python3 coding. In conditional if Statement the additional block of code is merged as else statement which is performed when if condition is false. Syntax: if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false Flow Chart:- Example 1: Python3 # if..else statement examplex = 3if x == 4: print("Yes")else: print("No") Output: No Example 2: You can also chain if..else statement with more than one condition. Python3 # if..else chain statementletter = "A" if letter == "B": print("letter is B") else: if letter == "C": print("letter is C") else: if letter == "A": print("letter is A") else: print("letter isn't A, B and C") Output: letter is A if statement can also be checked inside other if statement. This conditional statement is called a nested if statement. This means that inner if condition will be checked only if outer if condition is true and by this, we can see multiple conditions to be satisfied. Syntax: if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Flow chart:- Example: Python3 # Nested if statement examplenum = 10 if num > 5: print("Bigger than 5") if num <= 15: print("Between 5 and 15") Output: Bigger than 5 Between 5 and 15 The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block is added which is performed if none of the above if-elif statement is true. Syntax:- if (condition): statement elif (condition): statement . . else: statement Flow Chart:- Example:- Python3 # if-elif statement example letter = "A" if letter == B: print("letter is B") elif letter == "C": print("letter is C") elif num == "A": print("letter is A") else: print("letter isn't A, B or C") Output: letter is A rajeev0719singh akshaysingh98088 arorakashish0911 python-basics Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Apr, 2022" }, { "code": null, "e": 443, "s": 52, "text": "There comes situations in real life when we need to do some specific task and based on some specific conditions and, we decide what should we do next. Similarly there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditional statements provided by Python. " }, { "code": null, "e": 446, "s": 443, "text": "if" }, { "code": null, "e": 455, "s": 446, "text": "if..else" }, { "code": null, "e": 465, "s": 455, "text": "Nested if" }, { "code": null, "e": 485, "s": 465, "text": "if-elif statements." }, { "code": null, "e": 517, "s": 485, "text": "Let us go through all of them. " }, { "code": null, "e": 702, "s": 517, "text": "If the simple code of block is to be performed if the condition holds true then if statement is used. Here the condition mentioned holds true then the code of block runs otherwise not." }, { "code": null, "e": 711, "s": 702, "text": "Syntax: " }, { "code": null, "e": 789, "s": 711, "text": "if condition: \n # Statements to execute if\n # condition is true" }, { "code": null, "e": 802, "s": 789, "text": "Flowchart:- " }, { "code": null, "e": 813, "s": 802, "text": "Example: " }, { "code": null, "e": 821, "s": 813, "text": "Python3" }, { "code": "# if statement exampleif 10 > 5: print(\"10 greater than 5\") print(\"Program ended\")", "e": 906, "s": 821, "text": null }, { "code": null, "e": 915, "s": 906, "text": "Output: " }, { "code": null, "e": 947, "s": 915, "text": "10 greater than 5\nProgram ended" }, { "code": null, "e": 1094, "s": 947, "text": "Indentation(White space) is used to delimit the block of code. As shown in the above example it is mandatory to use indentation in Python3 coding." }, { "code": null, "e": 1227, "s": 1094, "text": "In conditional if Statement the additional block of code is merged as else statement which is performed when if condition is false. " }, { "code": null, "e": 1237, "s": 1227, "text": "Syntax: " }, { "code": null, "e": 1366, "s": 1237, "text": "if (condition):\n # Executes this block if\n # condition is true\nelse:\n # Executes this block if\n # condition is false" }, { "code": null, "e": 1380, "s": 1366, "text": "Flow Chart:- " }, { "code": null, "e": 1393, "s": 1380, "text": "Example 1: " }, { "code": null, "e": 1401, "s": 1393, "text": "Python3" }, { "code": "# if..else statement examplex = 3if x == 4: print(\"Yes\")else: print(\"No\")", "e": 1479, "s": 1401, "text": null }, { "code": null, "e": 1488, "s": 1479, "text": "Output: " }, { "code": null, "e": 1491, "s": 1488, "text": "No" }, { "code": null, "e": 1571, "s": 1491, "text": "Example 2: You can also chain if..else statement with more than one condition. " }, { "code": null, "e": 1579, "s": 1571, "text": "Python3" }, { "code": "# if..else chain statementletter = \"A\" if letter == \"B\": print(\"letter is B\") else: if letter == \"C\": print(\"letter is C\") else: if letter == \"A\": print(\"letter is A\") else: print(\"letter isn't A, B and C\")", "e": 1834, "s": 1579, "text": null }, { "code": null, "e": 1843, "s": 1834, "text": "Output: " }, { "code": null, "e": 1855, "s": 1843, "text": "letter is A" }, { "code": null, "e": 2122, "s": 1855, "text": "if statement can also be checked inside other if statement. This conditional statement is called a nested if statement. This means that inner if condition will be checked only if outer if condition is true and by this, we can see multiple conditions to be satisfied." }, { "code": null, "e": 2132, "s": 2122, "text": "Syntax: " }, { "code": null, "e": 2298, "s": 2132, "text": "if (condition1):\n # Executes when condition1 is true\n if (condition2): \n # Executes when condition2 is true\n # if Block is end here\n# if Block is end here" }, { "code": null, "e": 2312, "s": 2298, "text": "Flow chart:- " }, { "code": null, "e": 2322, "s": 2312, "text": "Example: " }, { "code": null, "e": 2330, "s": 2322, "text": "Python3" }, { "code": "# Nested if statement examplenum = 10 if num > 5: print(\"Bigger than 5\") if num <= 15: print(\"Between 5 and 15\")", "e": 2453, "s": 2330, "text": null }, { "code": null, "e": 2462, "s": 2453, "text": "Output: " }, { "code": null, "e": 2493, "s": 2462, "text": "Bigger than 5\nBetween 5 and 15" }, { "code": null, "e": 2674, "s": 2493, "text": "The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else block is added which is performed if none of the above if-elif statement is true." }, { "code": null, "e": 2685, "s": 2674, "text": "Syntax:- " }, { "code": null, "e": 2771, "s": 2685, "text": "if (condition):\n statement\nelif (condition):\n statement\n.\n.\nelse:\n statement" }, { "code": null, "e": 2786, "s": 2771, "text": "Flow Chart:- " }, { "code": null, "e": 2798, "s": 2786, "text": "Example:- " }, { "code": null, "e": 2806, "s": 2798, "text": "Python3" }, { "code": "# if-elif statement example letter = \"A\" if letter == B: print(\"letter is B\") elif letter == \"C\": print(\"letter is C\") elif num == \"A\": print(\"letter is A\") else: print(\"letter isn't A, B or C\")", "e": 3009, "s": 2806, "text": null }, { "code": null, "e": 3018, "s": 3009, "text": "Output: " }, { "code": null, "e": 3030, "s": 3018, "text": "letter is A" }, { "code": null, "e": 3048, "s": 3032, "text": "rajeev0719singh" }, { "code": null, "e": 3065, "s": 3048, "text": "akshaysingh98088" }, { "code": null, "e": 3082, "s": 3065, "text": "arorakashish0911" }, { "code": null, "e": 3096, "s": 3082, "text": "python-basics" }, { "code": null, "e": 3103, "s": 3096, "text": "Python" }, { "code": null, "e": 3119, "s": 3103, "text": "Write From Home" } ]
vector shrink_to_fit() function in C++ STL
09 Jun, 2022 The vector::shrink_to_fit() is a built-in function in C++ STL which reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. Syntax: vector_name.shrink_to_fit() Parameters: The function does not accept any parameters. Return value: The function does not returns anything. Time Complexity – Linear O(N) Below program illustrate the above function: CPP // C++ program to illustrate// the vector::shrink_to_fit()#include <bits/stdc++.h>using namespace std; int main(){ // Initialized vector vector<int> v(10); for (int i = 0; i < 10; i++) v[i] = i; // Initial vector cout << "Vector size initially: " << v.size(); cout << "\nVector elements are: "; for (int i = 0; i < 10; i++) cout << v[i] << " "; // changes the size of the Vector // but does not destroys the elements v.resize(5); cout << "\n\nVector size after resize(5): " << v.size(); cout << "\nVector elements after resize(5) are: "; for (int i = 0; i < 10; i++) cout << v[i] << " "; // Shrinks to the size // till which elements are // destroys the elements after 5 v.shrink_to_fit(); cout << "\n\nVector size after shrink_to_fit(): " << v.size(); cout << "\nVector elements after shrink_to_fit() are: "; for (int i = 0; i < 10; i++) cout << v[i] << " "; return 0;} Vector size initially: 10 Vector elements are: 0 1 2 3 4 5 6 7 8 9 Vector size after resize(5): 5 Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9 Vector size after shrink_to_fit(): 5 Vector elements after shrink_to_fit() are: 0 1 2 3 4 0 127889 0 0 0 AdityaKumawat1 utkarshgupta110092 CPP-Functions cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 230, "s": 53, "text": "The vector::shrink_to_fit() is a built-in function in C++ STL which reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. Syntax:" }, { "code": null, "e": 258, "s": 230, "text": "vector_name.shrink_to_fit()" }, { "code": null, "e": 370, "s": 258, "text": "Parameters: The function does not accept any parameters. Return value: The function does not returns anything. " }, { "code": null, "e": 400, "s": 370, "text": "Time Complexity – Linear O(N)" }, { "code": null, "e": 446, "s": 400, "text": "Below program illustrate the above function: " }, { "code": null, "e": 450, "s": 446, "text": "CPP" }, { "code": "// C++ program to illustrate// the vector::shrink_to_fit()#include <bits/stdc++.h>using namespace std; int main(){ // Initialized vector vector<int> v(10); for (int i = 0; i < 10; i++) v[i] = i; // Initial vector cout << \"Vector size initially: \" << v.size(); cout << \"\\nVector elements are: \"; for (int i = 0; i < 10; i++) cout << v[i] << \" \"; // changes the size of the Vector // but does not destroys the elements v.resize(5); cout << \"\\n\\nVector size after resize(5): \" << v.size(); cout << \"\\nVector elements after resize(5) are: \"; for (int i = 0; i < 10; i++) cout << v[i] << \" \"; // Shrinks to the size // till which elements are // destroys the elements after 5 v.shrink_to_fit(); cout << \"\\n\\nVector size after shrink_to_fit(): \" << v.size(); cout << \"\\nVector elements after shrink_to_fit() are: \"; for (int i = 0; i < 10; i++) cout << v[i] << \" \"; return 0;}", "e": 1429, "s": 450, "text": null }, { "code": null, "e": 1693, "s": 1429, "text": "Vector size initially: 10\nVector elements are: 0 1 2 3 4 5 6 7 8 9 \n\nVector size after resize(5): 5\nVector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9 \n\nVector size after shrink_to_fit(): 5\nVector elements after shrink_to_fit() are: 0 1 2 3 4 0 127889 0 0 0" }, { "code": null, "e": 1708, "s": 1693, "text": "AdityaKumawat1" }, { "code": null, "e": 1727, "s": 1708, "text": "utkarshgupta110092" }, { "code": null, "e": 1741, "s": 1727, "text": "CPP-Functions" }, { "code": null, "e": 1752, "s": 1741, "text": "cpp-vector" }, { "code": null, "e": 1756, "s": 1752, "text": "STL" }, { "code": null, "e": 1760, "s": 1756, "text": "C++" }, { "code": null, "e": 1764, "s": 1760, "text": "STL" }, { "code": null, "e": 1768, "s": 1764, "text": "CPP" } ]
How to Add Google Maps to a Website ?
12 Aug, 2021 The purpose of this article is to add Google Maps to a website. These are the following steps to add Google Maps to a website. Generate an API KeyCreate the HTML Container of the mapAdd an external script by google inside the HTML documentWrite JavaScript code to bring the map inside that container. Generate an API Key Create the HTML Container of the map Add an external script by google inside the HTML document Write JavaScript code to bring the map inside that container. 1. Generate an API Key To fetch the location data from google maps at first we need a Google Maps API Key. It is required to authorize the collection of the data from google maps. These are the steps to generate a Google Maps API Key: Visit the Google Map section of Google Cloud Console. Go to the credentials section of the menu on the left side-bar. Click on the ‘Create Credentials’ button below the navigation bar. Select ‘API KEY’ to generate a new API KEY. Copy the key and save it for future use. 2. Create an HTML Container for the map After the generation of API key we are going to create an HTML div. Inside that div our map will remain. We will do this in the following steps: Create a new HTML document. Inside the body section create an empty div, and give it a specific ID for styling purpose. In our example the specific ID given is ‘map’ as it is going to contain the map. Create a style tag and set the size of the div. 3. Add an external script by google inside the HTML document Add the following async script inside the HTML document as it executes immediately and must be after any DOM elements used in callback. Inside the script URL put the API key we generated earlier replacing the ‘<YOUR_API_KEY>’ section. <script src=“https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly”async></script> 4. Write JavaScript code to bring the map inside that container After the creation of the container we have to write the JavaScript code that actually brings the map inside the container. This is the main part where we generate the map. Initialize a function named initMap(). The name cannot be changed as this function name is the prebuilt indicator by Google which initializes and adds the map when the webpage loads. Inside that function initialize an object that contains the latitude and the longitude of the location that we are willing to show in the map. Create a new google.maps.Map object which takes the container element, the object which stores the center location and the zoom of the map. Example: HTML <!DOCTYPE html><html> <head> <style type="text/css"> /* Set the size of the div element that contains the map */ #map { height: 400px; width: 400px; } h2 { color: #308d46; } </style></head> <body> <h2> Add Google Map on Your Webpage: Geeksforgeeks </h2> <!--The div element for the map --> <div id="map"></div> <!--Add a script by google --> <script src="https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly" async> </script> <script> // Initialize and add the map function initMap() { // The location of Geeksforgeeks office const gfg_office = { lat: 28.50231, lng: 77.40548 }; // Create the map, centered at gfg_office const map = new google.maps.Map( document.getElementById("map"), { // Set the zoom of the map zoom: 17.56, center: gfg_office, }); } </script></body> </html> Output: HTML-Questions JavaScript-Questions Picked HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Aug, 2021" }, { "code": null, "e": 155, "s": 28, "text": "The purpose of this article is to add Google Maps to a website. These are the following steps to add Google Maps to a website." }, { "code": null, "e": 329, "s": 155, "text": "Generate an API KeyCreate the HTML Container of the mapAdd an external script by google inside the HTML documentWrite JavaScript code to bring the map inside that container." }, { "code": null, "e": 349, "s": 329, "text": "Generate an API Key" }, { "code": null, "e": 386, "s": 349, "text": "Create the HTML Container of the map" }, { "code": null, "e": 444, "s": 386, "text": "Add an external script by google inside the HTML document" }, { "code": null, "e": 506, "s": 444, "text": "Write JavaScript code to bring the map inside that container." }, { "code": null, "e": 529, "s": 506, "text": "1. Generate an API Key" }, { "code": null, "e": 741, "s": 529, "text": "To fetch the location data from google maps at first we need a Google Maps API Key. It is required to authorize the collection of the data from google maps. These are the steps to generate a Google Maps API Key:" }, { "code": null, "e": 796, "s": 741, "text": "Visit the Google Map section of Google Cloud Console." }, { "code": null, "e": 860, "s": 796, "text": "Go to the credentials section of the menu on the left side-bar." }, { "code": null, "e": 927, "s": 860, "text": "Click on the ‘Create Credentials’ button below the navigation bar." }, { "code": null, "e": 971, "s": 927, "text": "Select ‘API KEY’ to generate a new API KEY." }, { "code": null, "e": 1012, "s": 971, "text": "Copy the key and save it for future use." }, { "code": null, "e": 1054, "s": 1014, "text": "2. Create an HTML Container for the map" }, { "code": null, "e": 1199, "s": 1054, "text": "After the generation of API key we are going to create an HTML div. Inside that div our map will remain. We will do this in the following steps:" }, { "code": null, "e": 1227, "s": 1199, "text": "Create a new HTML document." }, { "code": null, "e": 1400, "s": 1227, "text": "Inside the body section create an empty div, and give it a specific ID for styling purpose. In our example the specific ID given is ‘map’ as it is going to contain the map." }, { "code": null, "e": 1448, "s": 1400, "text": "Create a style tag and set the size of the div." }, { "code": null, "e": 1509, "s": 1448, "text": "3. Add an external script by google inside the HTML document" }, { "code": null, "e": 1744, "s": 1509, "text": "Add the following async script inside the HTML document as it executes immediately and must be after any DOM elements used in callback. Inside the script URL put the API key we generated earlier replacing the ‘<YOUR_API_KEY>’ section." }, { "code": null, "e": 1869, "s": 1744, "text": "<script src=“https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly”async></script>" }, { "code": null, "e": 1933, "s": 1869, "text": "4. Write JavaScript code to bring the map inside that container" }, { "code": null, "e": 2106, "s": 1933, "text": "After the creation of the container we have to write the JavaScript code that actually brings the map inside the container. This is the main part where we generate the map." }, { "code": null, "e": 2289, "s": 2106, "text": "Initialize a function named initMap(). The name cannot be changed as this function name is the prebuilt indicator by Google which initializes and adds the map when the webpage loads." }, { "code": null, "e": 2432, "s": 2289, "text": "Inside that function initialize an object that contains the latitude and the longitude of the location that we are willing to show in the map." }, { "code": null, "e": 2572, "s": 2432, "text": "Create a new google.maps.Map object which takes the container element, the object which stores the center location and the zoom of the map." }, { "code": null, "e": 2581, "s": 2572, "text": "Example:" }, { "code": null, "e": 2586, "s": 2581, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> /* Set the size of the div element that contains the map */ #map { height: 400px; width: 400px; } h2 { color: #308d46; } </style></head> <body> <h2> Add Google Map on Your Webpage: Geeksforgeeks </h2> <!--The div element for the map --> <div id=\"map\"></div> <!--Add a script by google --> <script src=\"https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&callback=initMap&libraries=&v=weekly\" async> </script> <script> // Initialize and add the map function initMap() { // The location of Geeksforgeeks office const gfg_office = { lat: 28.50231, lng: 77.40548 }; // Create the map, centered at gfg_office const map = new google.maps.Map( document.getElementById(\"map\"), { // Set the zoom of the map zoom: 17.56, center: gfg_office, }); } </script></body> </html>", "e": 3749, "s": 2586, "text": null }, { "code": null, "e": 3757, "s": 3749, "text": "Output:" }, { "code": null, "e": 3772, "s": 3757, "text": "HTML-Questions" }, { "code": null, "e": 3793, "s": 3772, "text": "JavaScript-Questions" }, { "code": null, "e": 3800, "s": 3793, "text": "Picked" }, { "code": null, "e": 3805, "s": 3800, "text": "HTML" }, { "code": null, "e": 3816, "s": 3805, "text": "JavaScript" }, { "code": null, "e": 3833, "s": 3816, "text": "Web Technologies" }, { "code": null, "e": 3838, "s": 3833, "text": "HTML" } ]
Create a Numpy array filled with all ones
21 Feb, 2022 In this article, we will learn how to create a Numpy array filled with all one, given the shape and type of array. We can use Numpy.ones() method to do this task. This method takes three parameters, discussed below – shape : integer or sequence of integers order : C_contiguous or F_contiguous C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster. dtype : [optional, float(byDefault)] Data type of returned array. Code #1: Python3 # Python Program to create array with all onesimport numpy as geek a = geek.ones(3, dtype = int)print("Matrix a : \n", a) b = geek.ones([3, 3], dtype = int)print("\nMatrix b : \n", b) Output: Matrix a : [1 1 1] Matrix b : [[1 1 1] [1 1 1] [1 1 1]] Code #2: Python3 # Python Program to create array with all onesimport numpy as geek c = geek.ones([5, 3])print("\nMatrix c : \n", c) d = geek.ones([5, 2], dtype = float)print("\nMatrix d : \n", d) Output: Matrix c : [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] Matrix d : [[ 1. 1.] [ 1. 1.] [ 1. 1.] [ 1. 1.] [ 1. 1.]] avtarkumar719 Python numpy-program Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2022" }, { "code": null, "e": 247, "s": 28, "text": "In this article, we will learn how to create a Numpy array filled with all one, given the shape and type of array. We can use Numpy.ones() method to do this task. This method takes three parameters, discussed below – " }, { "code": null, "e": 693, "s": 247, "text": "shape : integer or sequence of integers\norder : C_contiguous or F_contiguous\n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \ndtype : [optional, float(byDefault)] Data type of returned array. " }, { "code": null, "e": 704, "s": 693, "text": "Code #1: " }, { "code": null, "e": 712, "s": 704, "text": "Python3" }, { "code": "# Python Program to create array with all onesimport numpy as geek a = geek.ones(3, dtype = int)print(\"Matrix a : \\n\", a) b = geek.ones([3, 3], dtype = int)print(\"\\nMatrix b : \\n\", b)", "e": 896, "s": 712, "text": null }, { "code": null, "e": 906, "s": 896, "text": "Output: " }, { "code": null, "e": 969, "s": 906, "text": "Matrix a : \n [1 1 1]\n\nMatrix b : \n [[1 1 1]\n [1 1 1]\n [1 1 1]]" }, { "code": null, "e": 982, "s": 969, "text": " Code #2: " }, { "code": null, "e": 990, "s": 982, "text": "Python3" }, { "code": "# Python Program to create array with all onesimport numpy as geek c = geek.ones([5, 3])print(\"\\nMatrix c : \\n\", c) d = geek.ones([5, 2], dtype = float)print(\"\\nMatrix d : \\n\", d)", "e": 1170, "s": 990, "text": null }, { "code": null, "e": 1180, "s": 1170, "text": "Output: " }, { "code": null, "e": 1339, "s": 1180, "text": "Matrix c : \n [[ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]\n [ 1. 1. 1.]]\n\nMatrix d : \n [[ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]\n [ 1. 1.]]" }, { "code": null, "e": 1355, "s": 1341, "text": "avtarkumar719" }, { "code": null, "e": 1376, "s": 1355, "text": "Python numpy-program" }, { "code": null, "e": 1389, "s": 1376, "text": "Python-numpy" }, { "code": null, "e": 1396, "s": 1389, "text": "Python" } ]
Modern Exploratory Data Analysis. Review of 4 libraries for automatic EDA | by ChiefHustler | Towards Data Science
EDA stands for Exploratory Data Analysis and is probably the most important yet most overlooked step in any data science project. My goal is to share with you some tools that will instantly 10x your productivity when exploring data. It’s during the exploration phase that the data scientists get close and intimate with the data set before moving on to data cleaning, feature engineering and modeling. Yet too many of us rush through data exploration and jump prematurely to the next steps. It used to be that you had to write home-cooked functions for EDA, and there has been a lot of reinventing the wheel and/or copy-pasting in this area. But with the advent of advanced techniques such as Automatic Machine Learning, it has become obvious that EDA could benefit from automation as well. In this post, I first show an example of the old fashioned way of doing EDA. Then I review the following packages that focus on making EDA as easy and efficient as possible: pandas-profiling (python) summarytools (R) explore (R) dataMaid (R) The data sets we’ll be using are: regression: health insurance, where the goal is to predict the insurance premium. classification: titanic, where the goal is to predict who survives. Install the R packages: install.packages(c("summarytools", "explore" "dataMaid")) Install the python pandas-profiling package: pip install pandas-profiling To use the package from Jupyter notebooks, we also need to run the following from the command-line: jupyter nbextension enable --py widgetsnbextension If you prefer Jupyter Lab, the command is instead: jupyterlab: jupyter labextension install @jupyter-widgets/jupyterlab-manager In the olden days, one would either use a visualization library or pandas built-in visualization functions. Let’see a few examples. import pandas as pd import numpy as np data = pd.read_csv('insurance.csv') This is probably the 1st function call in every data science notebook, used to peek at the data: data.head() This function gets us some summary statistics on each variable. I like to split the numeric and the categorical variables in two separate calls: data.describe(include=np.number) data.describe(include=np.object) The two most common plots for one-way distributions are bar charts for categorical variables and histograms for continuous variables. Both are easy to use directly from pandas: data['region'].value_counts().plot.barh(title='Region') data['age'].plot.hist(title='Age distribution') Finally, we have the ubiquitous correlation matrix: data.corr().style.background_gradient(cmap='coolwarm').set_precision(2) That concludes our quick review of old-school exploratory data analysis. As you can see, we have to explicitly write down every step. If the number of columns gets high, this process will either become tedious or we will have to write down our own functions to automate it. In the rest of the post, I review existing successful packages that can perform that automation for us. summarytools might be the easiest way to get 1-way information for every column in the dataset. library(summarytools) library(readr) df <- read_csv("insurance.csv") view(dfSummary(df)) The output is shown directly inside RStudio’s viewer, but you can also save it as an html file with the file parameter. Take a look:: Athough not comprehensive, I find this output extremely efficient in packing a lot of useful information in very little space. The package has a few other functions for univariate statistics and cross-tabulations, but the real gem in my opinion is the dfSummary function above. The explore package is quite incredible. For 1 line of code, you get a complete shiny application that lets you interactively explore your data. Let's see an example with the titanic data set. Below, I show one and two-way plots for 2 variables, a categorical one (Sex) and a continuous one (Age). We instantly see that women were much more likely to survive, and that young people were slightly more likely to survive: library(explore) df <- read_csv("titanic_train.csv") explore(df) Another nice feature is the “explain” tab where we can visualize a simple decision tree to build our intuition on the predictive variables: library('dataMaid') makeDataReport(df, render = FALSE, file = "output_file.Rmd", replace = TRUE) dataMaid is probably the most comprehensive option so far. You can output an Rmd file and then knit it into an HTML report from RStudio, or you can use render=TRUE which will output a nice Word document for you! The report starts with a summary table: Followed by a section for each variable. Here’s the section for bmi, which according to the summary table above might have a problem, which turns out to be a problem of potential outliers: The makeDataReport function has a lot of parameters to tweak the output. Overall, I'm very impressed with this package. Last but not least, pandas-profiling is probably the most popular package for automatic EDA in the python world. You can use it from within a notebook and thanks to the fantastic ipywidgets library, you get an interactive and very rich visualization to explore your data. from pandas_profiling import ProfileReport profile = ProfileReport(data, title='Pandas Profiling Report', html={'style':{'full_width':True}}) profile.to_widgets() First, you get an overview of the data: Along with a few warnings not caught by the previous packages: We also, we get a detailed report for each variable: And we can even toggle details for deeper exploration: Also available are interactions plots between the variables: The other tabs (Correlations, Missing values and Sample) are what you expect them to be. I invite you to play with this wonderful package. I hope I convinced you to stop using home-made functions or expensive visualization tools and switch to open-source dedicated packages. The 4 packages described above are my go-to tools for data exploration in a real-case setting. I start with the non-interactive ones, first summarytools followed by dataMaid. I then play around with explore, and finally, I spend the most time with pandas-profiling. This is how I get a familiar as possible with my data without wasting time writing boiler-plate code. Depending on the findings I come away with, I will use other packages for anomaly detection, imputation, feature engineering, etc. Each of these will be the subject of future posts. Thanks for reading!
[ { "code": null, "e": 301, "s": 171, "text": "EDA stands for Exploratory Data Analysis and is probably the most important yet most overlooked step in any data science project." }, { "code": null, "e": 404, "s": 301, "text": "My goal is to share with you some tools that will instantly 10x your productivity when exploring data." }, { "code": null, "e": 573, "s": 404, "text": "It’s during the exploration phase that the data scientists get close and intimate with the data set before moving on to data cleaning, feature engineering and modeling." }, { "code": null, "e": 662, "s": 573, "text": "Yet too many of us rush through data exploration and jump prematurely to the next steps." }, { "code": null, "e": 962, "s": 662, "text": "It used to be that you had to write home-cooked functions for EDA, and there has been a lot of reinventing the wheel and/or copy-pasting in this area. But with the advent of advanced techniques such as Automatic Machine Learning, it has become obvious that EDA could benefit from automation as well." }, { "code": null, "e": 1136, "s": 962, "text": "In this post, I first show an example of the old fashioned way of doing EDA. Then I review the following packages that focus on making EDA as easy and efficient as possible:" }, { "code": null, "e": 1162, "s": 1136, "text": "pandas-profiling (python)" }, { "code": null, "e": 1179, "s": 1162, "text": "summarytools (R)" }, { "code": null, "e": 1191, "s": 1179, "text": "explore (R)" }, { "code": null, "e": 1204, "s": 1191, "text": "dataMaid (R)" }, { "code": null, "e": 1238, "s": 1204, "text": "The data sets we’ll be using are:" }, { "code": null, "e": 1320, "s": 1238, "text": "regression: health insurance, where the goal is to predict the insurance premium." }, { "code": null, "e": 1388, "s": 1320, "text": "classification: titanic, where the goal is to predict who survives." }, { "code": null, "e": 1412, "s": 1388, "text": "Install the R packages:" }, { "code": null, "e": 1470, "s": 1412, "text": "install.packages(c(\"summarytools\", \"explore\" \"dataMaid\"))" }, { "code": null, "e": 1515, "s": 1470, "text": "Install the python pandas-profiling package:" }, { "code": null, "e": 1544, "s": 1515, "text": "pip install pandas-profiling" }, { "code": null, "e": 1644, "s": 1544, "text": "To use the package from Jupyter notebooks, we also need to run the following from the command-line:" }, { "code": null, "e": 1695, "s": 1644, "text": "jupyter nbextension enable --py widgetsnbextension" }, { "code": null, "e": 1746, "s": 1695, "text": "If you prefer Jupyter Lab, the command is instead:" }, { "code": null, "e": 1823, "s": 1746, "text": "jupyterlab: jupyter labextension install @jupyter-widgets/jupyterlab-manager" }, { "code": null, "e": 1955, "s": 1823, "text": "In the olden days, one would either use a visualization library or pandas built-in visualization functions. Let’see a few examples." }, { "code": null, "e": 2030, "s": 1955, "text": "import pandas as pd import numpy as np data = pd.read_csv('insurance.csv')" }, { "code": null, "e": 2127, "s": 2030, "text": "This is probably the 1st function call in every data science notebook, used to peek at the data:" }, { "code": null, "e": 2139, "s": 2127, "text": "data.head()" }, { "code": null, "e": 2284, "s": 2139, "text": "This function gets us some summary statistics on each variable. I like to split the numeric and the categorical variables in two separate calls:" }, { "code": null, "e": 2317, "s": 2284, "text": "data.describe(include=np.number)" }, { "code": null, "e": 2350, "s": 2317, "text": "data.describe(include=np.object)" }, { "code": null, "e": 2527, "s": 2350, "text": "The two most common plots for one-way distributions are bar charts for categorical variables and histograms for continuous variables. Both are easy to use directly from pandas:" }, { "code": null, "e": 2583, "s": 2527, "text": "data['region'].value_counts().plot.barh(title='Region')" }, { "code": null, "e": 2631, "s": 2583, "text": "data['age'].plot.hist(title='Age distribution')" }, { "code": null, "e": 2683, "s": 2631, "text": "Finally, we have the ubiquitous correlation matrix:" }, { "code": null, "e": 2755, "s": 2683, "text": "data.corr().style.background_gradient(cmap='coolwarm').set_precision(2)" }, { "code": null, "e": 3029, "s": 2755, "text": "That concludes our quick review of old-school exploratory data analysis. As you can see, we have to explicitly write down every step. If the number of columns gets high, this process will either become tedious or we will have to write down our own functions to automate it." }, { "code": null, "e": 3133, "s": 3029, "text": "In the rest of the post, I review existing successful packages that can perform that automation for us." }, { "code": null, "e": 3229, "s": 3133, "text": "summarytools might be the easiest way to get 1-way information for every column in the dataset." }, { "code": null, "e": 3318, "s": 3229, "text": "library(summarytools) library(readr) df <- read_csv(\"insurance.csv\") view(dfSummary(df))" }, { "code": null, "e": 3452, "s": 3318, "text": "The output is shown directly inside RStudio’s viewer, but you can also save it as an html file with the file parameter. Take a look::" }, { "code": null, "e": 3730, "s": 3452, "text": "Athough not comprehensive, I find this output extremely efficient in packing a lot of useful information in very little space. The package has a few other functions for univariate statistics and cross-tabulations, but the real gem in my opinion is the dfSummary function above." }, { "code": null, "e": 4150, "s": 3730, "text": "The explore package is quite incredible. For 1 line of code, you get a complete shiny application that lets you interactively explore your data. Let's see an example with the titanic data set. Below, I show one and two-way plots for 2 variables, a categorical one (Sex) and a continuous one (Age). We instantly see that women were much more likely to survive, and that young people were slightly more likely to survive:" }, { "code": null, "e": 4215, "s": 4150, "text": "library(explore) df <- read_csv(\"titanic_train.csv\") explore(df)" }, { "code": null, "e": 4355, "s": 4215, "text": "Another nice feature is the “explain” tab where we can visualize a simple decision tree to build our intuition on the predictive variables:" }, { "code": null, "e": 4511, "s": 4355, "text": "library('dataMaid') makeDataReport(df, render = FALSE, file = \"output_file.Rmd\", replace = TRUE)" }, { "code": null, "e": 4723, "s": 4511, "text": "dataMaid is probably the most comprehensive option so far. You can output an Rmd file and then knit it into an HTML report from RStudio, or you can use render=TRUE which will output a nice Word document for you!" }, { "code": null, "e": 4763, "s": 4723, "text": "The report starts with a summary table:" }, { "code": null, "e": 4952, "s": 4763, "text": "Followed by a section for each variable. Here’s the section for bmi, which according to the summary table above might have a problem, which turns out to be a problem of potential outliers:" }, { "code": null, "e": 5072, "s": 4952, "text": "The makeDataReport function has a lot of parameters to tweak the output. Overall, I'm very impressed with this package." }, { "code": null, "e": 5344, "s": 5072, "text": "Last but not least, pandas-profiling is probably the most popular package for automatic EDA in the python world. You can use it from within a notebook and thanks to the fantastic ipywidgets library, you get an interactive and very rich visualization to explore your data." }, { "code": null, "e": 5555, "s": 5344, "text": "from pandas_profiling import ProfileReport profile = ProfileReport(data, title='Pandas Profiling Report', html={'style':{'full_width':True}}) profile.to_widgets()" }, { "code": null, "e": 5595, "s": 5555, "text": "First, you get an overview of the data:" }, { "code": null, "e": 5658, "s": 5595, "text": "Along with a few warnings not caught by the previous packages:" }, { "code": null, "e": 5711, "s": 5658, "text": "We also, we get a detailed report for each variable:" }, { "code": null, "e": 5766, "s": 5711, "text": "And we can even toggle details for deeper exploration:" }, { "code": null, "e": 5827, "s": 5766, "text": "Also available are interactions plots between the variables:" }, { "code": null, "e": 5966, "s": 5827, "text": "The other tabs (Correlations, Missing values and Sample) are what you expect them to be. I invite you to play with this wonderful package." }, { "code": null, "e": 6102, "s": 5966, "text": "I hope I convinced you to stop using home-made functions or expensive visualization tools and switch to open-source dedicated packages." }, { "code": null, "e": 6368, "s": 6102, "text": "The 4 packages described above are my go-to tools for data exploration in a real-case setting. I start with the non-interactive ones, first summarytools followed by dataMaid. I then play around with explore, and finally, I spend the most time with pandas-profiling." } ]
Predicting Next Purchase Day. Machine Learning model to predict when... | by Barış Karaman | Towards Data Science
This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning. I will cover all the topics in the following nine articles: 1- Know Your Metrics 2- Customer Segmentation 3- Customer Lifetime Value Prediction 4- Churn Prediction 5- Predicting Next Purchase Day 6- Predicting Sales 7- Market Response Models 8- Uplift Modeling 9- A/B Testing Design and Execution Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it: Sometimes you gotta run before you can walk — Tony Stark As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only. Alright, let’s start. Most of the actions we explained in Data Driven Growth series have the same mentality behind: Treat your customers in a way they deserve before they expect that (e.g., LTV prediction) and act before something bad happens (e.g., churn). Predictive analytics helps us a lot on this one. One of the many opportunities it can provide is predicting the next purchase day of the customer. What if you know if a customer is likely to make another purchase in 7 days? We can build our strategy on top of that and come up with lots of tactical actions like: No promotional offer to this customer since s/he will make a purchase anyways Nudge the customer with inbound marketing if there is no purchase in the predicted time window (or fire the guy who did the prediction 🦹‍♀️ 🦹‍♂️ ) In this article, we will be using online retail dataset and follow the steps below: Data Wrangling (creating previous/next datasets and calculate purchase day differences) Feature Engineering Selecting a Machine Learning Model Multi-Classification Model Hyperparameter Tuning Let’s start with importing our data and do the preliminary data work: Importing CSV file and date field transformation We have imported the CSV file, converted the date field from string to DateTime to make it workable and filtered out countries other than the UK. To build our model, we should split our data into two parts: We use six months of behavioral data to predict customers’ first purchase date in the next three months. If there is no purchase, we will predict that too. Let’s assume our cut off date is Sep 9th ’11 and split the data: tx_6m = tx_uk[(tx_uk.InvoiceDate < date(2011,9,1)) & (tx_uk.InvoiceDate >= date(2011,3,1))].reset_index(drop=True)tx_next = tx_uk[(tx_uk.InvoiceDate >= date(2011,9,1)) & (tx_uk.InvoiceDate < date(2011,12,1))].reset_index(drop=True) tx_6m represents the six months performance whereas we will use tx_next for the find out the days between the last purchase date in tx_6m and the first one in tx_next. Also, we will create a dataframe called tx_user to possess a user-level feature set for the prediction model: tx_user = pd.DataFrame(tx_6m['CustomerID'].unique())tx_user.columns = ['CustomerID'] By using the data in tx_next, we need the calculate our label (days between last purchase before cut off date and first purchase after that): Now, tx_user looks like below: As you can easily notice, we have NaN values because those customers haven’t made any purchase yet. We fill NaN with 999 to quickly identify them later. We have customer ids and corresponding labels in a dataframe. Let’s enrich it with our feature set to build our machine learning model. For this project, we have selected our feature candidates like below: RFM scores & clusters Days between the last three purchases Mean & standard deviation of the difference between purchases in days After adding these features, we need to deal with the categorical features by applying get_dummies method. For RFM, to not repeat Part 2, we share the code block and move forward: Let’s focus on how we can add the next two features. We will be using shift() method a lot in this part. First, we create a dataframe with Customer ID and Invoice Day (not datetime). Then we will remove the duplicates since customers can do multiple purchases in a day and difference will become 0 for those. #create a dataframe with CustomerID and Invoice Datetx_day_order = tx_6m[['CustomerID','InvoiceDate']]#convert Invoice Datetime to daytx_day_order['InvoiceDay'] = tx_6m['InvoiceDate'].dt.datetx_day_order = tx_day_order.sort_values(['CustomerID','InvoiceDate'])#drop duplicatestx_day_order = tx_day_order.drop_duplicates(subset=['CustomerID','InvoiceDay'],keep='first') Next, by using shift, we create new columns with the dates of last 3 purchases and see how our dataframe looks like: #shifting last 3 purchase datestx_day_order['PrevInvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(1)tx_day_order['T2InvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(2)tx_day_order['T3InvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(3) Output: Let’s begin calculating the difference in days for each invoice date: tx_day_order['DayDiff'] = (tx_day_order['InvoiceDay'] - tx_day_order['PrevInvoiceDate']).dt.daystx_day_order['DayDiff2'] = (tx_day_order['InvoiceDay'] - tx_day_order['T2InvoiceDate']).dt.daystx_day_order['DayDiff3'] = (tx_day_order['InvoiceDay'] - tx_day_order['T3InvoiceDate']).dt.days Output: For each customer ID, we utilize .agg() method to find out the mean and standard deviation of the difference between purchases in days: tx_day_diff = tx_day_order.groupby('CustomerID').agg({'DayDiff': ['mean','std']}).reset_index()tx_day_diff.columns = ['CustomerID', 'DayDiffMean','DayDiffStd'] Now we are going to make a tough decision. The calculation above is quite useful for customers who have many purchases. But we can’t say the same for the ones with 1–2 purchases. For instance, it is too early to tag a customer as frequent who has only 2 purchases but back to back. We only keep customers who have > 3 purchases by using the following line: tx_day_order_last = tx_day_order.drop_duplicates(subset=['CustomerID'],keep='last') Finally, we drop NA values, merge new dataframes with tx_user and apply .get_dummies() for converting categorical values: tx_day_order_last = tx_day_order_last.dropna()tx_day_order_last = pd.merge(tx_day_order_last, tx_day_diff, on='CustomerID')tx_user = pd.merge(tx_user, tx_day_order_last[['CustomerID','DayDiff','DayDiff2','DayDiff3','DayDiffMean','DayDiffStd']], on='CustomerID')#create tx_class as a copy of tx_user before applying get_dummiestx_class = tx_user.copy()tx_class = pd.get_dummies(tx_class) Our feature set is ready for building a classification model. But there are many different models, which one should we use? Before jumping into choosing the model, we need to take two actions. First, we need to identify the classes in our label. Generally, percentiles give the right for that. Let’s use .describe() method to see them in NextPurchaseDay: Deciding the boundaries is a question for both statistics and business needs. It should make sense in terms of the first one and be easy to take action and communicate. Considering these two, we will have three classes: 0–20: Customers that will purchase in 0–20 days — Class name: 2 21–49: Customers that will purchase in 21–49 days — Class name: 1 ≥ 50: Customers that will purchase in more than 50 days — Class name: 0 tx_class['NextPurchaseDayRange'] = 2tx_class.loc[tx_class.NextPurchaseDay>20,'NextPurchaseDayRange'] = 1tx_class.loc[tx_class.NextPurchaseDay>50,'NextPurchaseDayRange'] = 0 The last step is to see the correlation between our features and label. The correlation matrix is one of the cleanest ways to show this: corr = tx_class[tx_class.columns].corr()plt.figure(figsize = (30,20))sns.heatmap(corr, annot = True, linewidths=0.2, fmt=".2f") Looks like Overall Score has the highest positive correlation (0.45) and Recency has the highest negative (-0.54). For this particular problem, we want to use the model which gives the highest accuracy. Let’s split train and test tests and measure the accuracy of different models: Accuracy per each model: From this result, we see that Naive Bayes is the best performing one (~64% accuracy). But before that, let’s look at what we did exactly. We applied a fundamental concept in Machine Learning, which is Cross Validation. How can we be sure of the stability of our machine learning model across different datasets? Also, what if there is a noise in the test set we selected. Cross Validation is a way of measuring this. It provides the score of the model by selecting different test sets. If the deviation is low, it means the model is stable. In our case, the deviations between scores are acceptable (except Decision Tree Classifier). Normally, we should go ahead with Naive Bayes. But for this example, let’s move forward with XGBoost to show how we can improve an existing model with some advanced techniques. To build our model, we will follow the steps in the previous articles. But for improving it further, we’ll do Hyperparameter Tuning. Programmatically, we will find out what are the best parameters for our model to make it provide the best accuracy. Let’s start with coding our model first: xgb_model = xgb.XGBClassifier().fit(X_train, y_train)print('Accuracy of XGB classifier on training set: {:.2f}' .format(xgb_model.score(X_train, y_train)))print('Accuracy of XGB classifier on test set: {:.2f}' .format(xgb_model.score(X_test[X_train.columns], y_test))) In this version, our accuracy on the test set is 58%: XGBClassifier has many parameters. You can find the list of them here. For this example, we will select max_depth and min_child_weight. The code below will generate the best values for these parameters: from sklearn.model_selection import GridSearchCVparam_test1 = { 'max_depth':range(3,10,2), 'min_child_weight':range(1,6,2)}gsearch1 = GridSearchCV(estimator = xgb.XGBClassifier(), param_grid = param_test1, scoring='accuracy',n_jobs=-1,iid=False, cv=2)gsearch1.fit(X_train,y_train)gsearch1.best_params_, gsearch1.best_score_ The algorithm says the best values are 3 and 5 for max_depth and min_child_weight respectively. Check out how it improves accuracy: Our score increased from 58% to 62%. It is quite an improvement. Knowing the next purchase day is a good indicator for predicting sales as well. We will be doing a deep dive on this topic in Part 6. You can find the Jupyter Notebook for this article here. To discuss growth marketing & data science, go ahead and book a free session with me here.
[ { "code": null, "e": 422, "s": 171, "text": "This series of articles was designed to explain how to use Python in a simplistic way to fuel your company’s growth by applying the predictive approach to all your actions. It will be a combination of programming, data analysis, and machine learning." }, { "code": null, "e": 482, "s": 422, "text": "I will cover all the topics in the following nine articles:" }, { "code": null, "e": 503, "s": 482, "text": "1- Know Your Metrics" }, { "code": null, "e": 528, "s": 503, "text": "2- Customer Segmentation" }, { "code": null, "e": 566, "s": 528, "text": "3- Customer Lifetime Value Prediction" }, { "code": null, "e": 586, "s": 566, "text": "4- Churn Prediction" }, { "code": null, "e": 618, "s": 586, "text": "5- Predicting Next Purchase Day" }, { "code": null, "e": 638, "s": 618, "text": "6- Predicting Sales" }, { "code": null, "e": 664, "s": 638, "text": "7- Market Response Models" }, { "code": null, "e": 683, "s": 664, "text": "8- Uplift Modeling" }, { "code": null, "e": 719, "s": 683, "text": "9- A/B Testing Design and Execution" }, { "code": null, "e": 1069, "s": 719, "text": "Articles will have their own code snippets to make you easily apply them. If you are super new to programming, you can have a good introduction for Python and Pandas (a famous library that we will use on everything) here. But still without a coding introduction, you can learn the concepts, how to use your data and start generating value out of it:" }, { "code": null, "e": 1126, "s": 1069, "text": "Sometimes you gotta run before you can walk — Tony Stark" }, { "code": null, "e": 1267, "s": 1126, "text": "As a pre-requisite, be sure Jupyter Notebook and Python are installed on your computer. The code snippets will run on Jupyter Notebook only." }, { "code": null, "e": 1289, "s": 1267, "text": "Alright, let’s start." }, { "code": null, "e": 1383, "s": 1289, "text": "Most of the actions we explained in Data Driven Growth series have the same mentality behind:" }, { "code": null, "e": 1525, "s": 1383, "text": "Treat your customers in a way they deserve before they expect that (e.g., LTV prediction) and act before something bad happens (e.g., churn)." }, { "code": null, "e": 1749, "s": 1525, "text": "Predictive analytics helps us a lot on this one. One of the many opportunities it can provide is predicting the next purchase day of the customer. What if you know if a customer is likely to make another purchase in 7 days?" }, { "code": null, "e": 1838, "s": 1749, "text": "We can build our strategy on top of that and come up with lots of tactical actions like:" }, { "code": null, "e": 1916, "s": 1838, "text": "No promotional offer to this customer since s/he will make a purchase anyways" }, { "code": null, "e": 2063, "s": 1916, "text": "Nudge the customer with inbound marketing if there is no purchase in the predicted time window (or fire the guy who did the prediction 🦹‍♀️ 🦹‍♂️ )" }, { "code": null, "e": 2147, "s": 2063, "text": "In this article, we will be using online retail dataset and follow the steps below:" }, { "code": null, "e": 2235, "s": 2147, "text": "Data Wrangling (creating previous/next datasets and calculate purchase day differences)" }, { "code": null, "e": 2255, "s": 2235, "text": "Feature Engineering" }, { "code": null, "e": 2290, "s": 2255, "text": "Selecting a Machine Learning Model" }, { "code": null, "e": 2317, "s": 2290, "text": "Multi-Classification Model" }, { "code": null, "e": 2339, "s": 2317, "text": "Hyperparameter Tuning" }, { "code": null, "e": 2409, "s": 2339, "text": "Let’s start with importing our data and do the preliminary data work:" }, { "code": null, "e": 2458, "s": 2409, "text": "Importing CSV file and date field transformation" }, { "code": null, "e": 2604, "s": 2458, "text": "We have imported the CSV file, converted the date field from string to DateTime to make it workable and filtered out countries other than the UK." }, { "code": null, "e": 2665, "s": 2604, "text": "To build our model, we should split our data into two parts:" }, { "code": null, "e": 2886, "s": 2665, "text": "We use six months of behavioral data to predict customers’ first purchase date in the next three months. If there is no purchase, we will predict that too. Let’s assume our cut off date is Sep 9th ’11 and split the data:" }, { "code": null, "e": 3118, "s": 2886, "text": "tx_6m = tx_uk[(tx_uk.InvoiceDate < date(2011,9,1)) & (tx_uk.InvoiceDate >= date(2011,3,1))].reset_index(drop=True)tx_next = tx_uk[(tx_uk.InvoiceDate >= date(2011,9,1)) & (tx_uk.InvoiceDate < date(2011,12,1))].reset_index(drop=True)" }, { "code": null, "e": 3286, "s": 3118, "text": "tx_6m represents the six months performance whereas we will use tx_next for the find out the days between the last purchase date in tx_6m and the first one in tx_next." }, { "code": null, "e": 3396, "s": 3286, "text": "Also, we will create a dataframe called tx_user to possess a user-level feature set for the prediction model:" }, { "code": null, "e": 3481, "s": 3396, "text": "tx_user = pd.DataFrame(tx_6m['CustomerID'].unique())tx_user.columns = ['CustomerID']" }, { "code": null, "e": 3623, "s": 3481, "text": "By using the data in tx_next, we need the calculate our label (days between last purchase before cut off date and first purchase after that):" }, { "code": null, "e": 3654, "s": 3623, "text": "Now, tx_user looks like below:" }, { "code": null, "e": 3807, "s": 3654, "text": "As you can easily notice, we have NaN values because those customers haven’t made any purchase yet. We fill NaN with 999 to quickly identify them later." }, { "code": null, "e": 3943, "s": 3807, "text": "We have customer ids and corresponding labels in a dataframe. Let’s enrich it with our feature set to build our machine learning model." }, { "code": null, "e": 4013, "s": 3943, "text": "For this project, we have selected our feature candidates like below:" }, { "code": null, "e": 4035, "s": 4013, "text": "RFM scores & clusters" }, { "code": null, "e": 4073, "s": 4035, "text": "Days between the last three purchases" }, { "code": null, "e": 4143, "s": 4073, "text": "Mean & standard deviation of the difference between purchases in days" }, { "code": null, "e": 4250, "s": 4143, "text": "After adding these features, we need to deal with the categorical features by applying get_dummies method." }, { "code": null, "e": 4323, "s": 4250, "text": "For RFM, to not repeat Part 2, we share the code block and move forward:" }, { "code": null, "e": 4428, "s": 4323, "text": "Let’s focus on how we can add the next two features. We will be using shift() method a lot in this part." }, { "code": null, "e": 4632, "s": 4428, "text": "First, we create a dataframe with Customer ID and Invoice Day (not datetime). Then we will remove the duplicates since customers can do multiple purchases in a day and difference will become 0 for those." }, { "code": null, "e": 5001, "s": 4632, "text": "#create a dataframe with CustomerID and Invoice Datetx_day_order = tx_6m[['CustomerID','InvoiceDate']]#convert Invoice Datetime to daytx_day_order['InvoiceDay'] = tx_6m['InvoiceDate'].dt.datetx_day_order = tx_day_order.sort_values(['CustomerID','InvoiceDate'])#drop duplicatestx_day_order = tx_day_order.drop_duplicates(subset=['CustomerID','InvoiceDay'],keep='first')" }, { "code": null, "e": 5118, "s": 5001, "text": "Next, by using shift, we create new columns with the dates of last 3 purchases and see how our dataframe looks like:" }, { "code": null, "e": 5419, "s": 5118, "text": "#shifting last 3 purchase datestx_day_order['PrevInvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(1)tx_day_order['T2InvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(2)tx_day_order['T3InvoiceDate'] = tx_day_order.groupby('CustomerID')['InvoiceDay'].shift(3)" }, { "code": null, "e": 5427, "s": 5419, "text": "Output:" }, { "code": null, "e": 5497, "s": 5427, "text": "Let’s begin calculating the difference in days for each invoice date:" }, { "code": null, "e": 5784, "s": 5497, "text": "tx_day_order['DayDiff'] = (tx_day_order['InvoiceDay'] - tx_day_order['PrevInvoiceDate']).dt.daystx_day_order['DayDiff2'] = (tx_day_order['InvoiceDay'] - tx_day_order['T2InvoiceDate']).dt.daystx_day_order['DayDiff3'] = (tx_day_order['InvoiceDay'] - tx_day_order['T3InvoiceDate']).dt.days" }, { "code": null, "e": 5792, "s": 5784, "text": "Output:" }, { "code": null, "e": 5928, "s": 5792, "text": "For each customer ID, we utilize .agg() method to find out the mean and standard deviation of the difference between purchases in days:" }, { "code": null, "e": 6088, "s": 5928, "text": "tx_day_diff = tx_day_order.groupby('CustomerID').agg({'DayDiff': ['mean','std']}).reset_index()tx_day_diff.columns = ['CustomerID', 'DayDiffMean','DayDiffStd']" }, { "code": null, "e": 6370, "s": 6088, "text": "Now we are going to make a tough decision. The calculation above is quite useful for customers who have many purchases. But we can’t say the same for the ones with 1–2 purchases. For instance, it is too early to tag a customer as frequent who has only 2 purchases but back to back." }, { "code": null, "e": 6445, "s": 6370, "text": "We only keep customers who have > 3 purchases by using the following line:" }, { "code": null, "e": 6529, "s": 6445, "text": "tx_day_order_last = tx_day_order.drop_duplicates(subset=['CustomerID'],keep='last')" }, { "code": null, "e": 6651, "s": 6529, "text": "Finally, we drop NA values, merge new dataframes with tx_user and apply .get_dummies() for converting categorical values:" }, { "code": null, "e": 7038, "s": 6651, "text": "tx_day_order_last = tx_day_order_last.dropna()tx_day_order_last = pd.merge(tx_day_order_last, tx_day_diff, on='CustomerID')tx_user = pd.merge(tx_user, tx_day_order_last[['CustomerID','DayDiff','DayDiff2','DayDiff3','DayDiffMean','DayDiffStd']], on='CustomerID')#create tx_class as a copy of tx_user before applying get_dummiestx_class = tx_user.copy()tx_class = pd.get_dummies(tx_class)" }, { "code": null, "e": 7162, "s": 7038, "text": "Our feature set is ready for building a classification model. But there are many different models, which one should we use?" }, { "code": null, "e": 7393, "s": 7162, "text": "Before jumping into choosing the model, we need to take two actions. First, we need to identify the classes in our label. Generally, percentiles give the right for that. Let’s use .describe() method to see them in NextPurchaseDay:" }, { "code": null, "e": 7613, "s": 7393, "text": "Deciding the boundaries is a question for both statistics and business needs. It should make sense in terms of the first one and be easy to take action and communicate. Considering these two, we will have three classes:" }, { "code": null, "e": 7677, "s": 7613, "text": "0–20: Customers that will purchase in 0–20 days — Class name: 2" }, { "code": null, "e": 7743, "s": 7677, "text": "21–49: Customers that will purchase in 21–49 days — Class name: 1" }, { "code": null, "e": 7815, "s": 7743, "text": "≥ 50: Customers that will purchase in more than 50 days — Class name: 0" }, { "code": null, "e": 7988, "s": 7815, "text": "tx_class['NextPurchaseDayRange'] = 2tx_class.loc[tx_class.NextPurchaseDay>20,'NextPurchaseDayRange'] = 1tx_class.loc[tx_class.NextPurchaseDay>50,'NextPurchaseDayRange'] = 0" }, { "code": null, "e": 8125, "s": 7988, "text": "The last step is to see the correlation between our features and label. The correlation matrix is one of the cleanest ways to show this:" }, { "code": null, "e": 8253, "s": 8125, "text": "corr = tx_class[tx_class.columns].corr()plt.figure(figsize = (30,20))sns.heatmap(corr, annot = True, linewidths=0.2, fmt=\".2f\")" }, { "code": null, "e": 8368, "s": 8253, "text": "Looks like Overall Score has the highest positive correlation (0.45) and Recency has the highest negative (-0.54)." }, { "code": null, "e": 8535, "s": 8368, "text": "For this particular problem, we want to use the model which gives the highest accuracy. Let’s split train and test tests and measure the accuracy of different models:" }, { "code": null, "e": 8560, "s": 8535, "text": "Accuracy per each model:" }, { "code": null, "e": 8779, "s": 8560, "text": "From this result, we see that Naive Bayes is the best performing one (~64% accuracy). But before that, let’s look at what we did exactly. We applied a fundamental concept in Machine Learning, which is Cross Validation." }, { "code": null, "e": 8932, "s": 8779, "text": "How can we be sure of the stability of our machine learning model across different datasets? Also, what if there is a noise in the test set we selected." }, { "code": null, "e": 9194, "s": 8932, "text": "Cross Validation is a way of measuring this. It provides the score of the model by selecting different test sets. If the deviation is low, it means the model is stable. In our case, the deviations between scores are acceptable (except Decision Tree Classifier)." }, { "code": null, "e": 9371, "s": 9194, "text": "Normally, we should go ahead with Naive Bayes. But for this example, let’s move forward with XGBoost to show how we can improve an existing model with some advanced techniques." }, { "code": null, "e": 9504, "s": 9371, "text": "To build our model, we will follow the steps in the previous articles. But for improving it further, we’ll do Hyperparameter Tuning." }, { "code": null, "e": 9620, "s": 9504, "text": "Programmatically, we will find out what are the best parameters for our model to make it provide the best accuracy." }, { "code": null, "e": 9661, "s": 9620, "text": "Let’s start with coding our model first:" }, { "code": null, "e": 9942, "s": 9661, "text": "xgb_model = xgb.XGBClassifier().fit(X_train, y_train)print('Accuracy of XGB classifier on training set: {:.2f}' .format(xgb_model.score(X_train, y_train)))print('Accuracy of XGB classifier on test set: {:.2f}' .format(xgb_model.score(X_test[X_train.columns], y_test)))" }, { "code": null, "e": 9996, "s": 9942, "text": "In this version, our accuracy on the test set is 58%:" }, { "code": null, "e": 10132, "s": 9996, "text": "XGBClassifier has many parameters. You can find the list of them here. For this example, we will select max_depth and min_child_weight." }, { "code": null, "e": 10199, "s": 10132, "text": "The code below will generate the best values for these parameters:" }, { "code": null, "e": 10523, "s": 10199, "text": "from sklearn.model_selection import GridSearchCVparam_test1 = { 'max_depth':range(3,10,2), 'min_child_weight':range(1,6,2)}gsearch1 = GridSearchCV(estimator = xgb.XGBClassifier(), param_grid = param_test1, scoring='accuracy',n_jobs=-1,iid=False, cv=2)gsearch1.fit(X_train,y_train)gsearch1.best_params_, gsearch1.best_score_" }, { "code": null, "e": 10655, "s": 10523, "text": "The algorithm says the best values are 3 and 5 for max_depth and min_child_weight respectively. Check out how it improves accuracy:" }, { "code": null, "e": 10720, "s": 10655, "text": "Our score increased from 58% to 62%. It is quite an improvement." }, { "code": null, "e": 10854, "s": 10720, "text": "Knowing the next purchase day is a good indicator for predicting sales as well. We will be doing a deep dive on this topic in Part 6." }, { "code": null, "e": 10911, "s": 10854, "text": "You can find the Jupyter Notebook for this article here." } ]
Plotting Data on Google Map using pygmaps package?
Python pygmaps library provides a wrapper for the google maps javascript api. With this library python users can create a matplotlib like interface to generate the html and javascript and then can depicts all the additional information user’s would like to add on top of Google Maps. We are only going to use the pygmaps library/package. You can install the pygmaps library using pip, like: $pip install pygmaps (windows os) $sudo pip3 install pygmaps (linux os) We are going to write a program which will display - Create a map using pygmaps by providing long, lat & zoom level. Create a map using pygmaps by providing long, lat & zoom level. Set grids on map by providing the start and end long & lat points for the grid and the grid size. Set grids on map by providing the start and end long & lat points for the grid and the grid size. Add a point on the map & display it by setting some color to it. Add a point on the map & display it by setting some color to it. Draw a circle around a point on the maps with a radius in meters. Draw a circle around a point on the maps with a radius in meters. Draw the path into a map by providing list of long & lat points. Draw the path into a map by providing list of long & lat points. Below is the implementation of getting different functionality through pygmaps. import pygmaps ########## CONSTRUCTOR: pygmaps.maps(latitude, longitude, zoom) ############################## # DESC:initialize a map with latitude and longitude of center point #and map zoom level "15" # PARAMETER1:latitude (float) latittude of map center point # PARAMETER2:longitude (float) latittude of map center point # PARAMETER3:zoom (int) map zoom level 0~20 # RETURN:the instant of pygmaps #======================================================================================== mymap = pygmaps.pygmaps(17.45,78.29, 15) ########## FUNCTION: setgrids(start-Lat, end-Lat, Lat-interval, start-Lng, end-Lng, Lng-interval) ###### # DESC:set grids on map # PARAMETER1:start-Lat (float), start (minimum) latittude of the grids # PARAMETER2:end-Lat (float), end (maximum) latittude of the grids # PARAMETER3:Lat-interval (float) grid size in latitude # PARAMETER4:start-Lng (float), start (minimum) longitude of the grids # PARAMETER5:end-Lng (float), end (maximum) longitude of the grids # PARAMETER6:Lng-interval (float) grid size in longitude # RETURN:no returns #======================================================================================== mymap.setgrids(17.45, 17.46, 0.001, 78.29,78.30, 0.001) ########## FUNCTION: addpoint(latitude, longitude, [color])############################# # DESC:add a point into a map and dispaly it, color is optional default is red # PARAMETER1:latitude (float) latitude of the point # PARAMETER2:longitude (float) longitude of the point # PARAMETER3:color (string) color of the point showed in map, using HTML color code #HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm #e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00" # RETURN:no return #======================================================================================== mymap.addpoint(17.45,78.29, "#FF0000","Hello") ########## FUNCTION: addradpoint(latitude, longitude, radius, [color])################## # DESC: add a point with a radius (Meter) - Draw cycle # PARAMETER1:latitude (float) latitude of the point # PARAMETER2:longitude (float) longitude of the point # PARAMETER3:radius (float), radius in meter # PARAMETER4:color (string) color of the point showed in map, using HTML color code #HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm #e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00" # RETURN:no return #======================================================================================== mymap.addradpoint(17.45,78.29, 150, "#0000FF") ########## FUNCTION: addpath(path,[color])############################################## # DESC:add a path into map, the data struceture of Path is a list of points # PARAMETER1:path (list of coordinates) e.g. [(lat1,lng1),(lat2,lng2),...] # PARAMETER2:color (string) color of the point showed in map, using HTML color code #HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm #e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00" # RETURN:no return #======================================================================================== path = [(17.45,78.29), (17.55, 78.39), (17.65,78.49), ] mymap.addpath(path,"#00FF00") ########## FUNCTION: draw(file)###################################################### # DESC:create the html map file (.html) # PARAMETER1:file (string) the map path and file # RETURN:no return, generate html file in specified directory #======================================================================================== mymap.draw('./mymap.html') print('OK') Note: You might encounter Typeerror while running mymap.addpoint function, something like TypeError: addpoint() takes from 3 to 4 positional arguments but 5 were given To avoid that I’ve added the title argument on the addpoint function of the pygmaps.py package. As you can see from the above maps, we are able to visualize multiple functionalities in a single map.
[ { "code": null, "e": 1346, "s": 1062, "text": "Python pygmaps library provides a wrapper for the google maps javascript api. With this library python users can create a matplotlib like interface to generate the html and javascript and then can depicts all the additional information user’s would like to add on top of Google Maps." }, { "code": null, "e": 1453, "s": 1346, "text": "We are only going to use the pygmaps library/package. You can install the pygmaps library using pip, like:" }, { "code": null, "e": 1525, "s": 1453, "text": "$pip install pygmaps (windows os)\n$sudo pip3 install pygmaps (linux os)" }, { "code": null, "e": 1578, "s": 1525, "text": "We are going to write a program which will display -" }, { "code": null, "e": 1642, "s": 1578, "text": "Create a map using pygmaps by providing long, lat & zoom level." }, { "code": null, "e": 1706, "s": 1642, "text": "Create a map using pygmaps by providing long, lat & zoom level." }, { "code": null, "e": 1804, "s": 1706, "text": "Set grids on map by providing the start and end long & lat points for the grid and the grid size." }, { "code": null, "e": 1902, "s": 1804, "text": "Set grids on map by providing the start and end long & lat points for the grid and the grid size." }, { "code": null, "e": 1967, "s": 1902, "text": "Add a point on the map & display it by setting some color to it." }, { "code": null, "e": 2032, "s": 1967, "text": "Add a point on the map & display it by setting some color to it." }, { "code": null, "e": 2098, "s": 2032, "text": "Draw a circle around a point on the maps with a radius in meters." }, { "code": null, "e": 2164, "s": 2098, "text": "Draw a circle around a point on the maps with a radius in meters." }, { "code": null, "e": 2229, "s": 2164, "text": "Draw the path into a map by providing list of long & lat points." }, { "code": null, "e": 2294, "s": 2229, "text": "Draw the path into a map by providing list of long & lat points." }, { "code": null, "e": 2374, "s": 2294, "text": "Below is the implementation of getting different functionality through pygmaps." }, { "code": null, "e": 5868, "s": 2374, "text": "import pygmaps\n########## CONSTRUCTOR: pygmaps.maps(latitude, longitude, zoom) ##############################\n# DESC:initialize a map with latitude and longitude of center point\n#and map zoom level \"15\"\n# PARAMETER1:latitude (float) latittude of map center point\n# PARAMETER2:longitude (float) latittude of map center point\n# PARAMETER3:zoom (int) map zoom level 0~20\n# RETURN:the instant of pygmaps\n#========================================================================================\nmymap = pygmaps.pygmaps(17.45,78.29, 15)\n\n\n########## FUNCTION: setgrids(start-Lat, end-Lat, Lat-interval, start-Lng, end-Lng, Lng-interval) ######\n# DESC:set grids on map\n# PARAMETER1:start-Lat (float), start (minimum) latittude of the grids\n# PARAMETER2:end-Lat (float), end (maximum) latittude of the grids\n# PARAMETER3:Lat-interval (float) grid size in latitude\n# PARAMETER4:start-Lng (float), start (minimum) longitude of the grids\n# PARAMETER5:end-Lng (float), end (maximum) longitude of the grids\n# PARAMETER6:Lng-interval (float) grid size in longitude\n# RETURN:no returns\n#========================================================================================\nmymap.setgrids(17.45, 17.46, 0.001, 78.29,78.30, 0.001)\n\n########## FUNCTION: addpoint(latitude, longitude, [color])#############################\n# DESC:add a point into a map and dispaly it, color is optional default is red\n# PARAMETER1:latitude (float) latitude of the point\n# PARAMETER2:longitude (float) longitude of the point\n# PARAMETER3:color (string) color of the point showed in map, using HTML color code\n#HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm\n#e.g. red \"#FF0000\", Blue \"#0000FF\", Green \"#00FF00\"\n# RETURN:no return\n#========================================================================================\nmymap.addpoint(17.45,78.29, \"#FF0000\",\"Hello\")\n\n\n########## FUNCTION: addradpoint(latitude, longitude, radius, [color])##################\n# DESC: add a point with a radius (Meter) - Draw cycle\n# PARAMETER1:latitude (float) latitude of the point\n# PARAMETER2:longitude (float) longitude of the point\n# PARAMETER3:radius (float), radius in meter\n# PARAMETER4:color (string) color of the point showed in map, using HTML color code\n#HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm\n#e.g. red \"#FF0000\", Blue \"#0000FF\", Green \"#00FF00\"\n# RETURN:no return\n#========================================================================================\nmymap.addradpoint(17.45,78.29, 150, \"#0000FF\")\n\n\n########## FUNCTION: addpath(path,[color])##############################################\n# DESC:add a path into map, the data struceture of Path is a list of points\n# PARAMETER1:path (list of coordinates) e.g. [(lat1,lng1),(lat2,lng2),...]\n# PARAMETER2:color (string) color of the point showed in map, using HTML color code\n#HTML COLOR CODE: http://www.computerhope.com/htmcolor.htm\n#e.g. red \"#FF0000\", Blue \"#0000FF\", Green \"#00FF00\"\n# RETURN:no return\n#========================================================================================\npath = [(17.45,78.29),\n(17.55, 78.39),\n(17.65,78.49),\n]\nmymap.addpath(path,\"#00FF00\")\n\n########## FUNCTION: draw(file)######################################################\n# DESC:create the html map file (.html)\n# PARAMETER1:file (string) the map path and file\n# RETURN:no return, generate html file in specified directory\n#========================================================================================\nmymap.draw('./mymap.html')\n\nprint('OK')" }, { "code": null, "e": 5958, "s": 5868, "text": "Note: You might encounter Typeerror while running mymap.addpoint function, something like" }, { "code": null, "e": 6036, "s": 5958, "text": "TypeError: addpoint() takes from 3 to 4 positional arguments but 5 were given" }, { "code": null, "e": 6132, "s": 6036, "text": "To avoid that I’ve added the title argument on the addpoint function of the pygmaps.py package." }, { "code": null, "e": 6235, "s": 6132, "text": "As you can see from the above maps, we are able to visualize multiple functionalities in a single map." } ]
How can I generate random number in a given range in Android?
This example demonstrates how do I generate random number in a given range on android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn_generate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/et_max" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:text="GENERATE" /> <EditText android:id="@+id/et_min" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:ems="10" android:hint="Minimum" android:inputType="number"/> <EditText android:id="@+id/et_max" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/et_min" android:layout_centerHorizontal="true" android:ems="10" android:hint="Maximum" android:inputType="number"/> <TextView android:id="@+id/tv_output" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/btn_generate" android:textSize="30dp" android:layout_centerHorizontal="true" android:hint="Output" android:text="" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity { EditText et_min, et_max; Button btn_generate; TextView tv_output; Random r; int min, max, output; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); r = new Random(); et_min = (EditText)findViewById(R.id.et_min); et_max = (EditText)findViewById(R.id.et_max); btn_generate = (Button)findViewById(R.id.btn_generate); tv_output = (TextView)findViewById(R.id.tv_output); btn_generate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tempMin, tempMax; tempMin = et_min.getText().toString(); tempMax = et_max.getText().toString(); if (!tempMin.equals("") &&!tempMax.equals("")){ min = Integer.parseInt(tempMin); max = Integer.parseInt(tempMax); if (max > min){ output = r.nextInt((max - min) +1) + min; tv_output.setText("" + output); } } } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1149, "s": 1062, "text": "This example demonstrates how do I generate random number in a given range on android." }, { "code": null, "e": 1278, "s": 1149, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1343, "s": 1278, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2846, "s": 1343, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/btn_generate\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/et_max\"\n android:layout_centerVertical=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"GENERATE\" />\n <EditText\n android:id=\"@+id/et_min\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:ems=\"10\"\n android:hint=\"Minimum\"\n android:inputType=\"number\"/>\n <EditText\n android:id=\"@+id/et_max\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/et_min\"\n android:layout_centerHorizontal=\"true\"\n android:ems=\"10\"\n android:hint=\"Maximum\"\n android:inputType=\"number\"/>\n <TextView\n android:id=\"@+id/tv_output\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btn_generate\"\n android:textSize=\"30dp\"\n android:layout_centerHorizontal=\"true\"\n android:hint=\"Output\"\n android:text=\"\" />\n</RelativeLayout>" }, { "code": null, "e": 2903, "s": 2846, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4315, "s": 2903, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport java.util.Random;\npublic class MainActivity extends AppCompatActivity {\n EditText et_min, et_max;\n Button btn_generate;\n TextView tv_output;\n Random r;\n int min, max, output;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n r = new Random();\n et_min = (EditText)findViewById(R.id.et_min);\n et_max = (EditText)findViewById(R.id.et_max);\n btn_generate = (Button)findViewById(R.id.btn_generate);\n tv_output = (TextView)findViewById(R.id.tv_output);\n btn_generate.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String tempMin, tempMax;\n tempMin = et_min.getText().toString();\n tempMax = et_max.getText().toString();\n if (!tempMin.equals(\"\") &&!tempMax.equals(\"\")){\n min = Integer.parseInt(tempMin);\n max = Integer.parseInt(tempMax);\n if (max > min){\n output = r.nextInt((max - min) +1) + min;\n tv_output.setText(\"\" + output);\n }\n }\n }\n });\n }\n}" }, { "code": null, "e": 4370, "s": 4315, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5040, "s": 4370, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5387, "s": 5040, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5428, "s": 5387, "text": "Click here to download the project code." } ]
JavaScript removeEventListener() method with examples
The JavaScript removeEventListener() method is used to remove an event listener from an element that has been previously attached with the addEventListener() method. Following is the code for removeEventListener() method − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample{ font-size: 18px; font-weight: 500; color:red; } </style> </head> <body> <h1>JavaScript removeEventListener() method</h1> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to print a number </h3> <button class="Btn">Remove event Listener</button> <h3>Click on the above button to remove the event listener of the first button</h3> <script> let sampleEle = document.querySelector('.sample'); let j=0; function printNum(){ sampleEle.innerHTML += 'Number = ' + j++ + '<br>'; } document.querySelector('.Btn').addEventListener('click',printNum); document.querySelectorAll('.Btn')[1].addEventListener('click',()=>{ document.querySelector('.Btn').removeEventListener('click',printNum); sampleEle.innerHTML = 'Event listener has been removed'; }) </script> </body> </html> The above code will produce the following output - On clicking ‘CLICK HERE’ three times − On clicking the ‘Remove event Listener’ button and clicking on the ‘CLICK HERE’ button again −
[ { "code": null, "e": 1228, "s": 1062, "text": "The JavaScript removeEventListener() method is used to remove an event listener from an element that has been previously attached with the addEventListener() method." }, { "code": null, "e": 1285, "s": 1228, "text": "Following is the code for removeEventListener() method −" }, { "code": null, "e": 1296, "s": 1285, "text": " Live Demo" }, { "code": null, "e": 2433, "s": 1296, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample{\n font-size: 18px;\n font-weight: 500;\n color:red;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript removeEventListener() method</h1>\n<div class=\"sample\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to print a number\n</h3>\n<button class=\"Btn\">Remove event Listener</button>\n<h3>Click on the above button to remove the event listener of the first button</h3>\n<script>\n let sampleEle = document.querySelector('.sample');\n let j=0;\n function printNum(){\n sampleEle.innerHTML += 'Number = ' + j++ + '<br>';\n }\n document.querySelector('.Btn').addEventListener('click',printNum);\n document.querySelectorAll('.Btn')[1].addEventListener('click',()=>{\n document.querySelector('.Btn').removeEventListener('click',printNum);\n sampleEle.innerHTML = 'Event listener has been removed';\n })\n</script>\n</body>\n</html>" }, { "code": null, "e": 2484, "s": 2433, "text": "The above code will produce the following output -" }, { "code": null, "e": 2523, "s": 2484, "text": "On clicking ‘CLICK HERE’ three times −" }, { "code": null, "e": 2618, "s": 2523, "text": "On clicking the ‘Remove event Listener’ button and clicking on the ‘CLICK HERE’ button again −" } ]
Excel’s CHOOSE Function with Array - GeeksforGeeks
29 Oct, 2021 The Excel CHOOSE function returns a value/reference from an array using a given position. Syntax: =CHOOSE (index_num, value1, [value2], ...) Arguments: index_num: The value to choose. value1: The first value from which to choose. value2 [optional]: The second value from which to choose. index_num: It is the first argument for CHOOSE function and it refers to the position of an array. Sample Data: In the Sales Table, we have given Products_Id. We use Excel CHOOSE() to fill Actual Products Name in the next column (Column – D). Sales Table Example 1: Returning a value Step 1: Type “Products” in cell D1 Step 2: Write a CHOOSE function in cell D2 =CHOOSE(C2,"Fashion","Electronics","Daily Essentials") Step 3: Select cell D2 and drag till cell D11 Example 2: Returning a cell reference Step 1: Type “Products” in cell D1 Step 2: Create a Product table (unique list of Products) in “Column H” Step 3: Write a CHOOSE function in cell D2 =CHOOSE(C2, $H$2,$H$3,$H$4) Step 4: Select cell D2 and drag till cell D11. Excel-functions Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Show Percentages in Stacked Column Chart in Excel? Macros in Excel Introduction to Excel Spreadsheet How to Get Length of Array in Excel VBA? How to Sum Values Based on Criteria in Another Column in Excel? Excel Dynamic Chart Linked with a Drop-down List How to Read Data From Text File in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel
[ { "code": null, "e": 25044, "s": 25016, "text": "\n29 Oct, 2021" }, { "code": null, "e": 25134, "s": 25044, "text": "The Excel CHOOSE function returns a value/reference from an array using a given position." }, { "code": null, "e": 25142, "s": 25134, "text": "Syntax:" }, { "code": null, "e": 25185, "s": 25142, "text": "=CHOOSE (index_num, value1, [value2], ...)" }, { "code": null, "e": 25198, "s": 25185, "text": "Arguments: " }, { "code": null, "e": 25230, "s": 25198, "text": "index_num: The value to choose." }, { "code": null, "e": 25276, "s": 25230, "text": "value1: The first value from which to choose." }, { "code": null, "e": 25334, "s": 25276, "text": "value2 [optional]: The second value from which to choose." }, { "code": null, "e": 25433, "s": 25334, "text": "index_num: It is the first argument for CHOOSE function and it refers to the position of an array." }, { "code": null, "e": 25578, "s": 25433, "text": "Sample Data: In the Sales Table, we have given Products_Id. We use Excel CHOOSE() to fill Actual Products Name in the next column (Column – D)." }, { "code": null, "e": 25590, "s": 25578, "text": "Sales Table" }, { "code": null, "e": 25619, "s": 25590, "text": "Example 1: Returning a value" }, { "code": null, "e": 25654, "s": 25619, "text": "Step 1: Type “Products” in cell D1" }, { "code": null, "e": 25699, "s": 25654, "text": "Step 2: Write a CHOOSE function in cell D2 " }, { "code": null, "e": 25754, "s": 25699, "text": "=CHOOSE(C2,\"Fashion\",\"Electronics\",\"Daily Essentials\")" }, { "code": null, "e": 25800, "s": 25754, "text": "Step 3: Select cell D2 and drag till cell D11" }, { "code": null, "e": 25838, "s": 25800, "text": "Example 2: Returning a cell reference" }, { "code": null, "e": 25873, "s": 25838, "text": "Step 1: Type “Products” in cell D1" }, { "code": null, "e": 25946, "s": 25873, "text": "Step 2: Create a Product table (unique list of Products) in “Column H” " }, { "code": null, "e": 25989, "s": 25946, "text": "Step 3: Write a CHOOSE function in cell D2" }, { "code": null, "e": 26017, "s": 25989, "text": "=CHOOSE(C2, $H$2,$H$3,$H$4)" }, { "code": null, "e": 26064, "s": 26017, "text": "Step 4: Select cell D2 and drag till cell D11." }, { "code": null, "e": 26080, "s": 26064, "text": "Excel-functions" }, { "code": null, "e": 26087, "s": 26080, "text": "Picked" }, { "code": null, "e": 26093, "s": 26087, "text": "Excel" }, { "code": null, "e": 26191, "s": 26093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26200, "s": 26191, "text": "Comments" }, { "code": null, "e": 26213, "s": 26200, "text": "Old Comments" }, { "code": null, "e": 26241, "s": 26213, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 26296, "s": 26241, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 26354, "s": 26296, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 26370, "s": 26354, "text": "Macros in Excel" }, { "code": null, "e": 26404, "s": 26370, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 26445, "s": 26404, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 26509, "s": 26445, "text": "How to Sum Values Based on Criteria in Another Column in Excel?" }, { "code": null, "e": 26558, "s": 26509, "text": "Excel Dynamic Chart Linked with a Drop-down List" }, { "code": null, "e": 26604, "s": 26558, "text": "How to Read Data From Text File in Excel VBA?" } ]
jQuery - Element Class Selector
The element class selector selects all the elements which match with the given class of the elements. Here is the simple syntax to use this selector − $('.classid') Here is the description of all the parameters used by this selector − classid − This is class ID available in the document. classid − This is class ID available in the document. Like any other jQuery selector, this selector also returns an array filled with the found elements. $('.big') − Selects all the elements with the given class ID big. $('.big') − Selects all the elements with the given class ID big. $('p.small') − Selects all the paragraphs with the given class ID small. $('p.small') − Selects all the paragraphs with the given class ID small. $('.big.small') − Selects all the elements with a class of big and small. $('.big.small') − Selects all the elements with a class of big and small. Following example would select all divisions with class .big and will apply yellow color to its background − <html> <head> <title>The Selecter Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { /* This would select second division only*/ $(".big").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" id="div1"> <p>This is first division of the DOM.</p> </div> <div class = "medium" id = "div2"> <p>This is second division of the DOM.</p> </div> <div class = "small" id = "div3"> <p>This is third division of the DOM</p> </div> </body> </html> This will produce following result − This is first division of the DOM. This is second division of the DOM. This is third division of the DOM 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2424, "s": 2322, "text": "The element class selector selects all the elements which match with the given class of the elements." }, { "code": null, "e": 2473, "s": 2424, "text": "Here is the simple syntax to use this selector −" }, { "code": null, "e": 2488, "s": 2473, "text": "$('.classid')\n" }, { "code": null, "e": 2558, "s": 2488, "text": "Here is the description of all the parameters used by this selector −" }, { "code": null, "e": 2612, "s": 2558, "text": "classid − This is class ID available in the document." }, { "code": null, "e": 2666, "s": 2612, "text": "classid − This is class ID available in the document." }, { "code": null, "e": 2766, "s": 2666, "text": "Like any other jQuery selector, this selector also returns an array filled with the found elements." }, { "code": null, "e": 2832, "s": 2766, "text": "$('.big') − Selects all the elements with the given class ID big." }, { "code": null, "e": 2898, "s": 2832, "text": "$('.big') − Selects all the elements with the given class ID big." }, { "code": null, "e": 2971, "s": 2898, "text": "$('p.small') − Selects all the paragraphs with the given class ID small." }, { "code": null, "e": 3044, "s": 2971, "text": "$('p.small') − Selects all the paragraphs with the given class ID small." }, { "code": null, "e": 3118, "s": 3044, "text": "$('.big.small') − Selects all the elements with a class of big and small." }, { "code": null, "e": 3192, "s": 3118, "text": "$('.big.small') − Selects all the elements with a class of big and small." }, { "code": null, "e": 3301, "s": 3192, "text": "Following example would select all divisions with class .big and will apply yellow color to its background −" }, { "code": null, "e": 4102, "s": 3301, "text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n /* This would select second division only*/\n $(\".big\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <div class = \"big\" id=\"div1\">\n <p>This is first division of the DOM.</p>\n </div>\n\n <div class = \"medium\" id = \"div2\">\n <p>This is second division of the DOM.</p>\n </div>\n\n <div class = \"small\" id = \"div3\">\n <p>This is third division of the DOM</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4139, "s": 4102, "text": "This will produce following result −" }, { "code": null, "e": 4174, "s": 4139, "text": "This is first division of the DOM." }, { "code": null, "e": 4210, "s": 4174, "text": "This is second division of the DOM." }, { "code": null, "e": 4244, "s": 4210, "text": "This is third division of the DOM" }, { "code": null, "e": 4277, "s": 4244, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4291, "s": 4277, "text": " Mahesh Kumar" }, { "code": null, "e": 4326, "s": 4291, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4340, "s": 4326, "text": " Pratik Singh" }, { "code": null, "e": 4375, "s": 4340, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4392, "s": 4375, "text": " Frahaan Hussain" }, { "code": null, "e": 4425, "s": 4392, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4453, "s": 4425, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4486, "s": 4453, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4507, "s": 4486, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4539, "s": 4507, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4556, "s": 4539, "text": " Laurence Svekis" }, { "code": null, "e": 4563, "s": 4556, "text": " Print" }, { "code": null, "e": 4574, "s": 4563, "text": " Add Notes" } ]
How to get local time and date in android using LocalDateTime API class?
This example demonstrate about How to get local time and date in android using LocalDateTime API class. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Local Date" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken textview to show time and date. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.date); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { LocalDateTime time = LocalDateTime.now(); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); dateTimeFormatter.format(time); textView.setText(String.valueOf("Date & Time " + time)); } } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, it is showing current time and date. Click here to download the project code
[ { "code": null, "e": 1166, "s": 1062, "text": "This example demonstrate about How to get local time and date in android using LocalDateTime API class." }, { "code": null, "e": 1295, "s": 1166, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1360, "s": 1295, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2137, "s": 1360, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2202, "s": 2137, "text": "In the above code, we have taken textview to show time and date." }, { "code": null, "e": 2259, "s": 2202, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3095, "s": 2259, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n LocalDateTime time = LocalDateTime.now();\n DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(\"dd-MM-yyyy HH:mm:ss\");\n dateTimeFormatter.format(time);\n textView.setText(String.valueOf(\"Date & Time \" + time));\n }\n }\n}" }, { "code": null, "e": 3442, "s": 3095, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 3500, "s": 3442, "text": "In the above result, it is showing current time and date." }, { "code": null, "e": 3540, "s": 3500, "text": "Click here to download the project code" } ]
Probability of Knight to remain in the chessboard - GeeksforGeeks
19 Apr, 2021 Given an NxN chessboard and a Knight at position (x,y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. What is the probability that the Knight remains in the chessboard after taking K steps, with the condition that it can’t enter the board again once it leaves it?Examples: Let's take: 8x8 chessboard, initial position of the knight : (0, 0), number of steps : 1 At each step, the Knight has 8 different positions to choose from. If it starts from (0, 0), after taking one step it will lie inside the board only at 2 out of 8 positions, and will lie outside at other positions. So, the probability is 2/8 = 0.25 Approach: One thing that we can observe is that at every step the Knight has 8 choices to choose from. Suppose, the Knight has to take k steps and after taking the Kth step the knight reaches (x,y). There are 8 different positions from where the Knight can reach to (x,y) in one step, and they are: (x+1,y+2), (x+2,y+1), (x+2,y-1), (x+1,y-2), (x-1,y-2), (x-2,y-1), (x-2,y+1), (x-1,y+2). What if we already knew the probabilities of reaching these 8 positions after K-1 steps? Then, the final probability after K steps will simply be equal to the (Σ probability of reaching each of these 8 positions after K-1 steps)/8; Here we are dividing by 8 because each of these 8 positions has 8 choices and position (x,y) is one of the choices. For the positions that lie outside the board, we will either take their probabilities as 0 or simply neglect it. Since we need to keep track of the probabilities at each position for every number of steps, we need Dynamic Programming to solve this problem. We are going to take an array dp[x][y][steps] which will store the probability of reaching (x,y) after (steps) number of moves. Base case: if the number of steps is 0, then the probability that the Knight will remain inside the board is 1.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the probability of the// Knight to remain inside the chessboard after// taking exactly K number of steps#include <bits/stdc++.h>using namespace std; // size of the chessboard#define N 8 // direction vector for the Knightint dx[] = { 1, 2, 2, 1, -1, -2, -2, -1 };int dy[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the knight is inside the chessboardbool inside(int x, int y){ return (x >= 0 and x < N and y >= 0 and y < N);} // Bottom up approach for finding the probability to// go out of chessboard.double findProb(int start_x, int start_y, int steps){ // dp array double dp1[N][N][steps + 1]; // for 0 number of steps, each position // will have probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (int s = 1; s <= steps; ++s) { // for every position (x,y) after // s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position reachable from (x,y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps];} // Driver Codeint main(){ // number of steps int K = 3; // Function Call cout << findProb(0, 0, K) << endl; return 0;} // Java program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of stepsclass GFG { // size of the chessboard static final int N = 8; // direction vector for the Knight static int dx[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; static int dy[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the knight is // inside the chessboard static boolean inside(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for finding // the probability to go out of // chessboard. static double findProb(int start_x, int start_y, int steps) { // dp array double dp1[][][] = new double[N][N][steps + 1]; // for 0 number of steps, each position // will have probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (int s = 1; s <= steps; ++s) { // for every position (x, y) after // s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position reachable // from (x, y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps]; } // Driver code public static void main(String[] args) { // number of steps int K = 3; // Function Call System.out.println(findProb(0, 0, K)); }} // This code is contributed by Anant Agarwal. # Python3 program to find the probability of# the Knight to remain inside the chessboard# after taking exactly K number of steps# size of the chessboardN = 8 # Direction vector for the Knightdx = [1, 2, 2, 1, -1, -2, -2, -1]dy = [2, 1, -1, -2, -2, -1, 1, 2] # returns true if the knight# is inside the chessboard def inside(x, y): return (x >= 0 and x < N and y >= 0 and y < N) # Bottom up approach for finding the# probability to go out of chessboard. def findProb(start_x, start_y, steps): # dp array dp1 = [[[0 for i in range(N+5)] for j in range(N+5)] for k in range(steps + 5)] # For 0 number of steps, each # position will have probability 1 for i in range(N): for j in range(N): dp1[i][j][0] = 1 # for every number of steps s for s in range(1, steps + 1): # for every position (x,y) after # s number of steps for x in range(N): for y in range(N): prob = 0.0 # For every position reachable from (x,y) for i in range(8): nx = x + dx[i] ny = y + dy[i] # if this position lie inside the board if (inside(nx, ny)): prob += dp1[nx][ny][s-1] / 8.0 # store the result dp1[x][y][s] = prob # return the result return dp1[start_x][start_y][steps] # Driver code # number of stepsK = 3 # Function Callprint(findProb(0, 0, K)) # This code is contributed by Anant Agarwal. // C# program to find the// probability of the Knight// to remain inside the// chessboard after taking// exactly K number of stepsusing System; class GFG { // size of the chessboard static int N = 8; // direction vector // for the Knight static int[] dx = { 1, 2, 2, 1, -1, -2, -2, -1 }; static int[] dy = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the // knight is inside the // chessboard static bool inside(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for // finding the probability // to go out of chessboard. static double findProb(int start_x, int start_y, int steps) { // dp array double[, , ] dp1 = new double[N, N, steps+1]; // for 0 number of steps, // each position will have // probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i, j, 0] = 1; // for every number // of steps s for (int s = 1; s <= steps; ++s) { // for every position (x, y) // after s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position // reachable from (x, y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx, ny, s - 1] / 8.0; } // store the result dp1[x, y, s] = prob; } } } // return the result return dp1[start_x, start_y, steps]; } // Driver code static void Main() { // number of steps int K = 3; // Function Call Console.WriteLine(findProb(0, 0, K)); }} // This code is contributed// by Sam007 <?php// PHP program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of steps // size of the chessboard$N = 8; // direction vector for the Knight$dx = array(1, 2, 2, 1, -1, -2, -2, -1 );$dy = array(2, 1, -1, -2, -2, -1, 1, 2 ); // returns true if the knight is// inside the chessboardfunction inside($x, $y){ global $N; return ($x >= 0 and $x < $N and $y >= 0 and $y < $N);} // Bottom up approach for finding the// probability to go out of chessboard.function findProb($start_x, $start_y, $steps){ global $N, $dx, $dy; // dp array $dp1 = array_fill(0, $N, array_fill(0, $N, array_fill(0, $steps+1, NULL))); // for 0 number of steps, each // position will have probability 1 for ($i = 0; $i < $N; ++$i) for ($j = 0; $j < $N; ++$j) $dp1[$i][$j][0] = 1; // for every number of steps s for ($s = 1; $s <= $steps; ++$s) { // for every position (x,y) after // s number of steps for ($x = 0; $x < $N; ++$x) { for ($y = 0; $y < $N; ++$y) { $prob = 0.0; // for every position // reachable from (x,y) for ($i = 0; $i < 8; ++$i) { $nx = $x + $dx[$i]; $ny = $y + $dy[$i]; // if this position lie inside // the board if (inside($nx, $ny)) $prob += $dp1[$nx][$ny][$s - 1] / 8.0; } // store the result $dp1[$x][$y][$s] = $prob; } } } // return the result return $dp1[$start_x][$start_y][$steps];} // Driver Code // number of steps$K = 3; // Function Callecho findProb(0, 0, $K) . "\n"; // This code is contributed by ita_c?> <script> // Javascript program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of steps // size of the chessboard let N = 8; // direction vector for the Knight let dx = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; let dy = [2, 1, -1, -2, -2, -1, 1, 2]; // returns true if the knight is // inside the chessboard function inside(x,y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for finding // the probability to go out of // chessboard. function findProb(start_x, start_y, steps) { // dp array let dp1 = new Array(N); for(let i = 0; i < N; i++) { dp1[i] = new Array(N); for(let j = 0; j < N; j++) { dp1[i][j] = new Array(steps + 1); for(let k = 0; k < steps + 1; k++) { dp1[i][j][k] = 0; } } } // for 0 number of steps, each position // will have probability 1 for (let i = 0; i < N; ++i) for (let j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (let s = 1; s <= steps; ++s) { // for every position (x, y) after // s number of steps for (let x = 0; x < N; ++x) { for (let y = 0; y < N; ++y) { let prob = 0.0; // for every position reachable // from (x, y) for (let i = 0; i < 8; ++i) { let nx = x + dx[i]; let ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps]; } // Driver code // number of steps let K = 3; // Function Call document.write(findProb(0, 0, K)); // This code is contributed by rag2127</script> 0.125 Time Complexity: O(NxNxKx8) which is O(NxNxK), where N is the size of the board and K is the number of steps. Space Complexity: O(NxNxK) This article is contributed by Avinash Kumar Saw. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 ukasp anshmittal rag2127 Amazon chessboard-problems Directi Probability Dynamic Programming Amazon Directi Dynamic Programming Probability Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Matrix Chain Multiplication | DP-8 Sieve of Eratosthenes Edit Distance | DP-5 Overlapping Subproblems Property in Dynamic Programming | DP-1 Minimum number of jumps to reach end Efficient program to print all prime factors of a given number
[ { "code": null, "e": 25122, "s": 25094, "text": "\n19 Apr, 2021" }, { "code": null, "e": 25465, "s": 25122, "text": "Given an NxN chessboard and a Knight at position (x,y). The Knight has to take exactly K steps, where at each step it chooses any of the 8 directions uniformly at random. What is the probability that the Knight remains in the chessboard after taking K steps, with the condition that it can’t enter the board again once it leaves it?Examples: " }, { "code": null, "e": 25805, "s": 25465, "text": "Let's take:\n8x8 chessboard,\ninitial position of the knight : (0, 0),\nnumber of steps : 1\nAt each step, the Knight has 8 different positions to choose from. \n\nIf it starts from (0, 0), after taking one step it will lie inside the\nboard only at 2 out of 8 positions, and will lie outside at other positions.\nSo, the probability is 2/8 = 0.25" }, { "code": null, "e": 25815, "s": 25805, "text": "Approach:" }, { "code": null, "e": 26282, "s": 25815, "text": "One thing that we can observe is that at every step the Knight has 8 choices to choose from. Suppose, the Knight has to take k steps and after taking the Kth step the knight reaches (x,y). There are 8 different positions from where the Knight can reach to (x,y) in one step, and they are: (x+1,y+2), (x+2,y+1), (x+2,y-1), (x+1,y-2), (x-1,y-2), (x-2,y-1), (x-2,y+1), (x-1,y+2). What if we already knew the probabilities of reaching these 8 positions after K-1 steps? " }, { "code": null, "e": 26426, "s": 26282, "text": "Then, the final probability after K steps will simply be equal to the (Σ probability of reaching each of these 8 positions after K-1 steps)/8; " }, { "code": null, "e": 26543, "s": 26426, "text": "Here we are dividing by 8 because each of these 8 positions has 8 choices and position (x,y) is one of the choices. " }, { "code": null, "e": 26656, "s": 26543, "text": "For the positions that lie outside the board, we will either take their probabilities as 0 or simply neglect it." }, { "code": null, "e": 26929, "s": 26656, "text": "Since we need to keep track of the probabilities at each position for every number of steps, we need Dynamic Programming to solve this problem. We are going to take an array dp[x][y][steps] which will store the probability of reaching (x,y) after (steps) number of moves. " }, { "code": null, "e": 27092, "s": 26929, "text": "Base case: if the number of steps is 0, then the probability that the Knight will remain inside the board is 1.Below is the implementation of the above approach: " }, { "code": null, "e": 27096, "s": 27092, "text": "C++" }, { "code": null, "e": 27101, "s": 27096, "text": "Java" }, { "code": null, "e": 27109, "s": 27101, "text": "Python3" }, { "code": null, "e": 27112, "s": 27109, "text": "C#" }, { "code": null, "e": 27116, "s": 27112, "text": "PHP" }, { "code": null, "e": 27127, "s": 27116, "text": "Javascript" }, { "code": "// C++ program to find the probability of the// Knight to remain inside the chessboard after// taking exactly K number of steps#include <bits/stdc++.h>using namespace std; // size of the chessboard#define N 8 // direction vector for the Knightint dx[] = { 1, 2, 2, 1, -1, -2, -2, -1 };int dy[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the knight is inside the chessboardbool inside(int x, int y){ return (x >= 0 and x < N and y >= 0 and y < N);} // Bottom up approach for finding the probability to// go out of chessboard.double findProb(int start_x, int start_y, int steps){ // dp array double dp1[N][N][steps + 1]; // for 0 number of steps, each position // will have probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (int s = 1; s <= steps; ++s) { // for every position (x,y) after // s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position reachable from (x,y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps];} // Driver Codeint main(){ // number of steps int K = 3; // Function Call cout << findProb(0, 0, K) << endl; return 0;}", "e": 28854, "s": 27127, "text": null }, { "code": "// Java program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of stepsclass GFG { // size of the chessboard static final int N = 8; // direction vector for the Knight static int dx[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; static int dy[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the knight is // inside the chessboard static boolean inside(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for finding // the probability to go out of // chessboard. static double findProb(int start_x, int start_y, int steps) { // dp array double dp1[][][] = new double[N][N][steps + 1]; // for 0 number of steps, each position // will have probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (int s = 1; s <= steps; ++s) { // for every position (x, y) after // s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position reachable // from (x, y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps]; } // Driver code public static void main(String[] args) { // number of steps int K = 3; // Function Call System.out.println(findProb(0, 0, K)); }} // This code is contributed by Anant Agarwal.", "e": 30999, "s": 28854, "text": null }, { "code": "# Python3 program to find the probability of# the Knight to remain inside the chessboard# after taking exactly K number of steps# size of the chessboardN = 8 # Direction vector for the Knightdx = [1, 2, 2, 1, -1, -2, -2, -1]dy = [2, 1, -1, -2, -2, -1, 1, 2] # returns true if the knight# is inside the chessboard def inside(x, y): return (x >= 0 and x < N and y >= 0 and y < N) # Bottom up approach for finding the# probability to go out of chessboard. def findProb(start_x, start_y, steps): # dp array dp1 = [[[0 for i in range(N+5)] for j in range(N+5)] for k in range(steps + 5)] # For 0 number of steps, each # position will have probability 1 for i in range(N): for j in range(N): dp1[i][j][0] = 1 # for every number of steps s for s in range(1, steps + 1): # for every position (x,y) after # s number of steps for x in range(N): for y in range(N): prob = 0.0 # For every position reachable from (x,y) for i in range(8): nx = x + dx[i] ny = y + dy[i] # if this position lie inside the board if (inside(nx, ny)): prob += dp1[nx][ny][s-1] / 8.0 # store the result dp1[x][y][s] = prob # return the result return dp1[start_x][start_y][steps] # Driver code # number of stepsK = 3 # Function Callprint(findProb(0, 0, K)) # This code is contributed by Anant Agarwal.", "e": 32549, "s": 30999, "text": null }, { "code": "// C# program to find the// probability of the Knight// to remain inside the// chessboard after taking// exactly K number of stepsusing System; class GFG { // size of the chessboard static int N = 8; // direction vector // for the Knight static int[] dx = { 1, 2, 2, 1, -1, -2, -2, -1 }; static int[] dy = { 2, 1, -1, -2, -2, -1, 1, 2 }; // returns true if the // knight is inside the // chessboard static bool inside(int x, int y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for // finding the probability // to go out of chessboard. static double findProb(int start_x, int start_y, int steps) { // dp array double[, , ] dp1 = new double[N, N, steps+1]; // for 0 number of steps, // each position will have // probability 1 for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) dp1[i, j, 0] = 1; // for every number // of steps s for (int s = 1; s <= steps; ++s) { // for every position (x, y) // after s number of steps for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { double prob = 0.0; // for every position // reachable from (x, y) for (int i = 0; i < 8; ++i) { int nx = x + dx[i]; int ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx, ny, s - 1] / 8.0; } // store the result dp1[x, y, s] = prob; } } } // return the result return dp1[start_x, start_y, steps]; } // Driver code static void Main() { // number of steps int K = 3; // Function Call Console.WriteLine(findProb(0, 0, K)); }} // This code is contributed// by Sam007", "e": 34699, "s": 32549, "text": null }, { "code": "<?php// PHP program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of steps // size of the chessboard$N = 8; // direction vector for the Knight$dx = array(1, 2, 2, 1, -1, -2, -2, -1 );$dy = array(2, 1, -1, -2, -2, -1, 1, 2 ); // returns true if the knight is// inside the chessboardfunction inside($x, $y){ global $N; return ($x >= 0 and $x < $N and $y >= 0 and $y < $N);} // Bottom up approach for finding the// probability to go out of chessboard.function findProb($start_x, $start_y, $steps){ global $N, $dx, $dy; // dp array $dp1 = array_fill(0, $N, array_fill(0, $N, array_fill(0, $steps+1, NULL))); // for 0 number of steps, each // position will have probability 1 for ($i = 0; $i < $N; ++$i) for ($j = 0; $j < $N; ++$j) $dp1[$i][$j][0] = 1; // for every number of steps s for ($s = 1; $s <= $steps; ++$s) { // for every position (x,y) after // s number of steps for ($x = 0; $x < $N; ++$x) { for ($y = 0; $y < $N; ++$y) { $prob = 0.0; // for every position // reachable from (x,y) for ($i = 0; $i < 8; ++$i) { $nx = $x + $dx[$i]; $ny = $y + $dy[$i]; // if this position lie inside // the board if (inside($nx, $ny)) $prob += $dp1[$nx][$ny][$s - 1] / 8.0; } // store the result $dp1[$x][$y][$s] = $prob; } } } // return the result return $dp1[$start_x][$start_y][$steps];} // Driver Code // number of steps$K = 3; // Function Callecho findProb(0, 0, $K) . \"\\n\"; // This code is contributed by ita_c?>", "e": 36574, "s": 34699, "text": null }, { "code": "<script> // Javascript program to find the probability// of the Knight to remain inside the// chessboard after taking exactly K// number of steps // size of the chessboard let N = 8; // direction vector for the Knight let dx = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; let dy = [2, 1, -1, -2, -2, -1, 1, 2]; // returns true if the knight is // inside the chessboard function inside(x,y) { return (x >= 0 && x < N && y >= 0 && y < N); } // Bottom up approach for finding // the probability to go out of // chessboard. function findProb(start_x, start_y, steps) { // dp array let dp1 = new Array(N); for(let i = 0; i < N; i++) { dp1[i] = new Array(N); for(let j = 0; j < N; j++) { dp1[i][j] = new Array(steps + 1); for(let k = 0; k < steps + 1; k++) { dp1[i][j][k] = 0; } } } // for 0 number of steps, each position // will have probability 1 for (let i = 0; i < N; ++i) for (let j = 0; j < N; ++j) dp1[i][j][0] = 1; // for every number of steps s for (let s = 1; s <= steps; ++s) { // for every position (x, y) after // s number of steps for (let x = 0; x < N; ++x) { for (let y = 0; y < N; ++y) { let prob = 0.0; // for every position reachable // from (x, y) for (let i = 0; i < 8; ++i) { let nx = x + dx[i]; let ny = y + dy[i]; // if this position lie // inside the board if (inside(nx, ny)) prob += dp1[nx][ny][s - 1] / 8.0; } // store the result dp1[x][y][s] = prob; } } } // return the result return dp1[start_x][start_y][steps]; } // Driver code // number of steps let K = 3; // Function Call document.write(findProb(0, 0, K)); // This code is contributed by rag2127</script>", "e": 38984, "s": 36574, "text": null }, { "code": null, "e": 38990, "s": 38984, "text": "0.125" }, { "code": null, "e": 39127, "s": 38990, "text": "Time Complexity: O(NxNxKx8) which is O(NxNxK), where N is the size of the board and K is the number of steps. Space Complexity: O(NxNxK)" }, { "code": null, "e": 39553, "s": 39127, "text": "This article is contributed by Avinash Kumar Saw. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39560, "s": 39553, "text": "Sam007" }, { "code": null, "e": 39566, "s": 39560, "text": "ukasp" }, { "code": null, "e": 39577, "s": 39566, "text": "anshmittal" }, { "code": null, "e": 39585, "s": 39577, "text": "rag2127" }, { "code": null, "e": 39592, "s": 39585, "text": "Amazon" }, { "code": null, "e": 39612, "s": 39592, "text": "chessboard-problems" }, { "code": null, "e": 39620, "s": 39612, "text": "Directi" }, { "code": null, "e": 39632, "s": 39620, "text": "Probability" }, { "code": null, "e": 39652, "s": 39632, "text": "Dynamic Programming" }, { "code": null, "e": 39659, "s": 39652, "text": "Amazon" }, { "code": null, "e": 39667, "s": 39659, "text": "Directi" }, { "code": null, "e": 39687, "s": 39667, "text": "Dynamic Programming" }, { "code": null, "e": 39699, "s": 39687, "text": "Probability" }, { "code": null, "e": 39797, "s": 39699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39806, "s": 39797, "text": "Comments" }, { "code": null, "e": 39819, "s": 39806, "text": "Old Comments" }, { "code": null, "e": 39850, "s": 39819, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 39883, "s": 39850, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 39951, "s": 39883, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 39989, "s": 39951, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 40024, "s": 39989, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 40046, "s": 40024, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 40067, "s": 40046, "text": "Edit Distance | DP-5" }, { "code": null, "e": 40130, "s": 40067, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" }, { "code": null, "e": 40167, "s": 40130, "text": "Minimum number of jumps to reach end" } ]
How to support webview with multiple screens in android?
This example demonstrate about How to support webview with multiple screens in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <WebView android:id = "@+id/web_view" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken web view to show tutorialspoint.com. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ProgressDialog; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading Data..."); progressDialog.setCancelable(false); WebView web_view = findViewById(R.id.web_view); web_view.requestFocus(); web_view.getSettings().setJavaScriptEnabled(true); // How to support webview with multiple screens in android web_view.getSettings().setSupportMultipleWindows(true); web_view.loadUrl("https://www.tutorialspoint.com/"); web_view.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { if (progress < 100) { progressDialog.show(); } if (progress = = 100) { progressDialog.dismiss(); } } }); } } Step 4 − Add the following code to AndroidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1150, "s": 1062, "text": "This example demonstrate about How to support webview with multiple screens in android." }, { "code": null, "e": 1279, "s": 1150, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1344, "s": 1279, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1911, "s": 1344, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1981, "s": 1911, "text": "In the above code, we have taken web view to show tutorialspoint.com." }, { "code": null, "e": 2038, "s": 1981, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3499, "s": 2038, "text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setJavaScriptEnabled(true);\n // How to support webview with multiple screens in android\n web_view.getSettings().setSupportMultipleWindows(true);\n web_view.loadUrl(\"https://www.tutorialspoint.com/\");\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}" }, { "code": null, "e": 3554, "s": 3499, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 4331, "s": 3554, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4678, "s": 4331, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4718, "s": 4678, "text": "Click here to download the project code" } ]
Count of substrings of a Binary string containing only 1s - GeeksforGeeks
30 Mar, 2022 Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = “0110111”Output: 9Explanation:There are 9 substring with only 1’s characters. “1” comes 5 times. “11” comes 3 times. “111” comes 1 time. Input: S = “000”Output: 0 Approach: The idea is to traverse the binary string and count the consecutive ones in the string. Below is the illustration of the approach: Traverse the given binary string from index 0 to length – 1 Count the number of consecutive “1” till index i. For each new character str[i], there will be more substring with all character’s as “1” Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find// count of substring containing// only ones #include <bits/stdc++.h>using namespace std; // Function to find the total number// of substring having only onesint countOfSubstringWithOnlyOnes(string s){ int res = 0, count = 0; for (int i = 0; i < s.length(); i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver Codeint main(){ string s = "0110111"; cout << countOfSubstringWithOnlyOnes(s) << endl; return 0;} // Java implementation to find// count of substring containing// only onesclass GFG{ // Function to find the total number// of substring having only onesstatic int countOfSubstringWithOnlyOnes(String s){ int res = 0, count = 0; for(int i = 0; i < s.length(); i++) { count = s.charAt(i) == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver codepublic static void main(String[] args){ String s = "0110111"; System.out.println(countOfSubstringWithOnlyOnes(s));}} // This code is contributed by dewantipandeydp # Python3 implementation to find# count of substring containing# only ones # Function to find the total number# of substring having only onesdef countOfSubstringWithOnlyOnes(s): count = 0 res = 0 for i in range(0,len(s)): if s[i] == '1': count = count + 1 else: count = 0; res = res + count return res # Driver Codes = "0110111"print(countOfSubstringWithOnlyOnes(s)) # This code is contributed by jojo9911 // C# implementation to find count// of substring containing only onesusing System; class GFG{ // Function to find the total number// of substring having only onesstatic int countOfSubstringWithOnlyOnes(string s){ int res = 0, count = 0; for(int i = 0; i < s.Length; i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver codepublic static void Main(string[] args){ string s = "0110111"; Console.Write(countOfSubstringWithOnlyOnes(s));}} // This code is contributed by rutvik_56 <script> // Javascript implementation to find// count of substring containing// only ones // Function to find the total number// of substring having only onesfunction countOfSubstringWithOnlyOnes(s){ var res = 0, count = 0; for (var i = 0; i < s.length; i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver Codevar s = "0110111";document.write( countOfSubstringWithOnlyOnes(s)); </script> 9 Time Complexity: O(n), where n is the size of the given stringAuxiliary Space: O(1) dewantipandeydp jojo9911 rutvik_56 itsok singhh3010 binary-string substring Bit Magic Mathematical Strings Strings Mathematical 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 Check whether K-th bit is set or not Program to find parity Write an Efficient Method to Check if a Number is Multiple of 3 Hamming code Implementation in C/C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25014, "s": 24986, "text": "\n30 Mar, 2022" }, { "code": null, "e": 25121, "s": 25014, "text": "Given a binary string of length N, we need to find out how many substrings of this string contain only 1s." }, { "code": null, "e": 25132, "s": 25121, "text": "Examples: " }, { "code": null, "e": 25280, "s": 25132, "text": "Input: S = “0110111”Output: 9Explanation:There are 9 substring with only 1’s characters. “1” comes 5 times. “11” comes 3 times. “111” comes 1 time." }, { "code": null, "e": 25306, "s": 25280, "text": "Input: S = “000”Output: 0" }, { "code": null, "e": 25447, "s": 25306, "text": "Approach: The idea is to traverse the binary string and count the consecutive ones in the string. Below is the illustration of the approach:" }, { "code": null, "e": 25507, "s": 25447, "text": "Traverse the given binary string from index 0 to length – 1" }, { "code": null, "e": 25557, "s": 25507, "text": "Count the number of consecutive “1” till index i." }, { "code": null, "e": 25645, "s": 25557, "text": "For each new character str[i], there will be more substring with all character’s as “1”" }, { "code": null, "e": 25696, "s": 25645, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25700, "s": 25696, "text": "C++" }, { "code": null, "e": 25705, "s": 25700, "text": "Java" }, { "code": null, "e": 25713, "s": 25705, "text": "Python3" }, { "code": null, "e": 25716, "s": 25713, "text": "C#" }, { "code": null, "e": 25727, "s": 25716, "text": "Javascript" }, { "code": "// C++ implementation to find// count of substring containing// only ones #include <bits/stdc++.h>using namespace std; // Function to find the total number// of substring having only onesint countOfSubstringWithOnlyOnes(string s){ int res = 0, count = 0; for (int i = 0; i < s.length(); i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver Codeint main(){ string s = \"0110111\"; cout << countOfSubstringWithOnlyOnes(s) << endl; return 0;}", "e": 26236, "s": 25727, "text": null }, { "code": "// Java implementation to find// count of substring containing// only onesclass GFG{ // Function to find the total number// of substring having only onesstatic int countOfSubstringWithOnlyOnes(String s){ int res = 0, count = 0; for(int i = 0; i < s.length(); i++) { count = s.charAt(i) == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver codepublic static void main(String[] args){ String s = \"0110111\"; System.out.println(countOfSubstringWithOnlyOnes(s));}} // This code is contributed by dewantipandeydp", "e": 26804, "s": 26236, "text": null }, { "code": "# Python3 implementation to find# count of substring containing# only ones # Function to find the total number# of substring having only onesdef countOfSubstringWithOnlyOnes(s): count = 0 res = 0 for i in range(0,len(s)): if s[i] == '1': count = count + 1 else: count = 0; res = res + count return res # Driver Codes = \"0110111\"print(countOfSubstringWithOnlyOnes(s)) # This code is contributed by jojo9911", "e": 27297, "s": 26804, "text": null }, { "code": "// C# implementation to find count// of substring containing only onesusing System; class GFG{ // Function to find the total number// of substring having only onesstatic int countOfSubstringWithOnlyOnes(string s){ int res = 0, count = 0; for(int i = 0; i < s.Length; i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver codepublic static void Main(string[] args){ string s = \"0110111\"; Console.Write(countOfSubstringWithOnlyOnes(s));}} // This code is contributed by rutvik_56", "e": 27860, "s": 27297, "text": null }, { "code": "<script> // Javascript implementation to find// count of substring containing// only ones // Function to find the total number// of substring having only onesfunction countOfSubstringWithOnlyOnes(s){ var res = 0, count = 0; for (var i = 0; i < s.length; i++) { count = s[i] == '1' ? count + 1 : 0; res = (res + count); } return res;} // Driver Codevar s = \"0110111\";document.write( countOfSubstringWithOnlyOnes(s)); </script>", "e": 28304, "s": 27860, "text": null }, { "code": null, "e": 28306, "s": 28304, "text": "9" }, { "code": null, "e": 28390, "s": 28306, "text": "Time Complexity: O(n), where n is the size of the given stringAuxiliary Space: O(1)" }, { "code": null, "e": 28406, "s": 28390, "text": "dewantipandeydp" }, { "code": null, "e": 28415, "s": 28406, "text": "jojo9911" }, { "code": null, "e": 28425, "s": 28415, "text": "rutvik_56" }, { "code": null, "e": 28431, "s": 28425, "text": "itsok" }, { "code": null, "e": 28442, "s": 28431, "text": "singhh3010" }, { "code": null, "e": 28456, "s": 28442, "text": "binary-string" }, { "code": null, "e": 28466, "s": 28456, "text": "substring" }, { "code": null, "e": 28476, "s": 28466, "text": "Bit Magic" }, { "code": null, "e": 28489, "s": 28476, "text": "Mathematical" }, { "code": null, "e": 28497, "s": 28489, "text": "Strings" }, { "code": null, "e": 28505, "s": 28497, "text": "Strings" }, { "code": null, "e": 28518, "s": 28505, "text": "Mathematical" }, { "code": null, "e": 28528, "s": 28518, "text": "Bit Magic" }, { "code": null, "e": 28626, "s": 28528, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28677, "s": 28626, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 28714, "s": 28677, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 28737, "s": 28714, "text": "Program to find parity" }, { "code": null, "e": 28801, "s": 28737, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 28838, "s": 28801, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 28868, "s": 28838, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 28928, "s": 28868, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28943, "s": 28928, "text": "C++ Data Types" }, { "code": null, "e": 28986, "s": 28943, "text": "Set in C++ Standard Template Library (STL)" } ]
GATE | GATE-CS-2015 (Set 2) | Question 40
28 Jun, 2021 Consider six memory partitions of size 200 KB, 400 KB, 600 KB, 500 KB, 300 KB, and 250 KB, where KB refers to kilobyte. These partitions need to be allotted to four processes of sizes 357 KB, 210 KB, 468 KB and 491 KB in that order. If the best fit algorithm is used, which partitions are NOT allotted to any process? (A) 200 KB and 300 KB(B) 200 KB and 250 KB(C) 250 KB and 300 KB(D) 300 KB and 400 KBAnswer: (A)Explanation: Best fit allocates the smallest block among those that are large enough for the new process. So the memory blocks are allocated in below order. 357 ---> 400 210 ---> 250 468 ---> 500 491 ---> 600 Sot the remaining blocks are of 200 KB and 300 KB Refer http://courses.cs.vt.edu/~csonline/OS/Lessons/MemoryAllocation/index.html for details of all allocation strategies.Quiz of this Question GATE-CS-2015 (Set 2) GATE-GATE-CS-2015 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-1) | Question 51 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2015 (Set 2) | Question 55 GATE | GATE-CS-2004 | Question 31 GATE | GATE-CS-2001 | Question 50
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 372, "s": 54, "text": "Consider six memory partitions of size 200 KB, 400 KB, 600 KB, 500 KB, 300 KB, and 250 KB, where KB refers to kilobyte. These partitions need to be allotted to four processes of sizes 357 KB, 210 KB, 468 KB and 491 KB in that order. If the best fit algorithm is used, which partitions are NOT allotted to any process?" }, { "code": null, "e": 624, "s": 372, "text": "(A) 200 KB and 300 KB(B) 200 KB and 250 KB(C) 250 KB and 300 KB(D) 300 KB and 400 KBAnswer: (A)Explanation: Best fit allocates the smallest block among those that are large enough for the new process. So the memory blocks are allocated in below order." }, { "code": null, "e": 676, "s": 624, "text": "357 ---> 400\n210 ---> 250\n468 ---> 500\n491 ---> 600" }, { "code": null, "e": 726, "s": 676, "text": "Sot the remaining blocks are of 200 KB and 300 KB" }, { "code": null, "e": 869, "s": 726, "text": "Refer http://courses.cs.vt.edu/~csonline/OS/Lessons/MemoryAllocation/index.html for details of all allocation strategies.Quiz of this Question" }, { "code": null, "e": 890, "s": 869, "text": "GATE-CS-2015 (Set 2)" }, { "code": null, "e": 916, "s": 890, "text": "GATE-GATE-CS-2015 (Set 2)" }, { "code": null, "e": 921, "s": 916, "text": "GATE" }, { "code": null, "e": 1019, "s": 921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1061, "s": 1019, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1123, "s": 1061, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1157, "s": 1123, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1199, "s": 1157, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1241, "s": 1199, "text": "GATE | GATE-CS-2014-(Set-1) | Question 51" }, { "code": null, "e": 1283, "s": 1241, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1317, "s": 1283, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1359, "s": 1317, "text": "GATE | GATE-CS-2015 (Set 2) | Question 55" }, { "code": null, "e": 1393, "s": 1359, "text": "GATE | GATE-CS-2004 | Question 31" } ]
Box Plot
22 Jan, 2021 Box Plot: It is a type of chart that depicts a group of numerical data through their quartiles. It is a simple way to visualize the shape of our data. It makes comparing characteristics of data between categories very easy. In this article, we are going to discuss the following topics- Understanding the components of a box plotHow to create a box plotUses of a Box PlotHow to compare box plots Understanding the components of a box plot How to create a box plot Uses of a Box Plot How to compare box plots Let’s proceed further step by step 1) Understanding the components of a box plot A box plot gives a five-number summary of a set of data which is- Minimum – It is the minimum value in the dataset excluding the outliers First Quartile (Q1) – 25% of the data lies below the First (lower) Quartile. Median (Q2) – It is the mid-point of the dataset. Half of the values lie below it and half above. Third Quartile (Q3) – 75% of the data lies below the Third (Upper) Quartile. Maximum – It is the maximum value in the dataset excluding the outliers. Note: The box plot shown in the above diagram is a perfect plot with no skewness. The plots can have skewness and the median might not be at the center of the box. The area inside the box (50% of the data) is known as the Inter Quartile Range. The IQR is calculated as – IQR = Q3-Q1 Outliers are the data points below and above the lower and upper limit. The lower and upper limit is calculated as – Lower Limit = Q1 - 1.5*IQR Upper Limit = Q3 + 1.5*IQR The values below and above these limits are considered outliers and the minimum and maximum values are calculated from the points which lie under the lower and upper limit. 2) How to create a box plot Let us take a sample data to understand how to create a box plot. Here are the runs scored by a cricket team in a league of 12 matches – 100,120,110,150,110,140,130,170,120,220,140,110. To draw a box plot for the given data first we need to arrange the data in ascending order and then find the minimum, first quartile, median, third quartile and the maximum. Ascending Order - 100,110,110,110,120,120,130,140,140,150,170,220 Median (Q2) = (120+130)/2 = 125 ; Since there were even values To find the First Quartile we take the first six values and find their median. Q1 = (110+110)/2 = 110 For the Third Quartile, we take the next six and find their median. Q3 = (140+150)/2 = 145 Note: If the total number of values is odd then we exclude the Median while calculating Q1 and Q3. Here since there were two central values we included them. Now, we need to calculate the Inter Quartile Range. IQR = Q3-Q1 = 145-110 = 35 We can now calculate the Upper and Lower Limits to find the minimum and maximum values and also the outliers if any. Lower Limit = Q1-1.5*IQR = 110-1.5*35 = 57.5 Upper Limit = Q3+1.5*IQR = 145+1.5*35 = 197.5 So the minimum and maximum between the range [57.5,197.5] for our given data are – Minimum = 100 Maximum = 170 The outliers which are outside this range are – Outliers = 220 Now we have all the information, so we can draw the box plot which is as below- We can see from the diagram that the Median is not exactly at the centre of the box and one whisker is longer than the other. We also have one Outlier. 3) Uses of a Box Plot Box plots provide a visual summary of the data with which we can quickly identify the average value of the data, how dispersed the data is, whether the data is skewed or not (skewness). The Median gives you the average value of the data. Box Plots shows Skewness of the data- a) If the Median is at the center of the Box and the whiskers are almost the same on both the ends then the data is Normally Distributed. b) If the Median lies closer to the First Quartile and if the whisker at the lower end is shorter (as in the above example) then it has a Positive Skew (Right Skew). c) If the Median lies closer to the Third Quartile and if the whisker at the upper end is shorter then it has a Negative Skew (Left Skew). The dispersion or spread of data can be visualized by the minimum and maximum values which are found at the end of the whiskers. The Box plot gives us the idea of about the Outliers which are the points which are numerically distant from the rest of the data. 4) How to compare box plots As we have discussed at the beginning of the article that box plots make comparing characteristics of data between categories very easy. Let us have a look at how we can compare different box plots and derive statistical conclusions from them. Let us take the below two plots as an example:- Compare the Medians — If the median line of a box plot lies outside the box of the other box plot with which it is being compared, then we can say that there is likely to be a difference between the two groups. Here the Median line of the plot B lies outside the box of Plot A. Compare the Dispersion or Spread of data — The Inter Quartile range (length of the box) gives us an idea about how dispersed the data is. Here Plot A has a longer length than Plot B which means that the dispersion of data is more in plot A as compared to plot B. The length of whiskers also gives an idea of the overall spread of data. The extreme values (minimum &maximum) gives the range of data distribution. Larger the range more scattered the data. Here Plot A has a larger range than Plot B. Comparing Outliers — The outliers gives the idea of unusual data values which are distant from the rest of the data. More number of Outliers means the prediction will be more uncertain. We can be more confident while predicting the values for a plot which has less or no outliers. Compare Skewness — Skewness gives us the direction and the magnitude of the lack of symmetry. We have discussed above how to identify skewness. Here Plot A is Positive or Right Skewed and Plot B is Negative or Left Skewed. This is all for Box Plots. Now you might have got the idea of Box Plots how to make them and how to derive information from them. For any queries do leave a comment down below. Data Visualization ML-EDA ML-plots Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI Intuition of Adam Optimizer
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2021" }, { "code": null, "e": 252, "s": 28, "text": "Box Plot: It is a type of chart that depicts a group of numerical data through their quartiles. It is a simple way to visualize the shape of our data. It makes comparing characteristics of data between categories very easy." }, { "code": null, "e": 315, "s": 252, "text": "In this article, we are going to discuss the following topics-" }, { "code": null, "e": 424, "s": 315, "text": "Understanding the components of a box plotHow to create a box plotUses of a Box PlotHow to compare box plots" }, { "code": null, "e": 467, "s": 424, "text": "Understanding the components of a box plot" }, { "code": null, "e": 492, "s": 467, "text": "How to create a box plot" }, { "code": null, "e": 511, "s": 492, "text": "Uses of a Box Plot" }, { "code": null, "e": 536, "s": 511, "text": "How to compare box plots" }, { "code": null, "e": 571, "s": 536, "text": "Let’s proceed further step by step" }, { "code": null, "e": 617, "s": 571, "text": "1) Understanding the components of a box plot" }, { "code": null, "e": 683, "s": 617, "text": "A box plot gives a five-number summary of a set of data which is-" }, { "code": null, "e": 755, "s": 683, "text": "Minimum – It is the minimum value in the dataset excluding the outliers" }, { "code": null, "e": 832, "s": 755, "text": "First Quartile (Q1) – 25% of the data lies below the First (lower) Quartile." }, { "code": null, "e": 930, "s": 832, "text": "Median (Q2) – It is the mid-point of the dataset. Half of the values lie below it and half above." }, { "code": null, "e": 1007, "s": 930, "text": "Third Quartile (Q3) – 75% of the data lies below the Third (Upper) Quartile." }, { "code": null, "e": 1080, "s": 1007, "text": "Maximum – It is the maximum value in the dataset excluding the outliers." }, { "code": null, "e": 1244, "s": 1080, "text": "Note: The box plot shown in the above diagram is a perfect plot with no skewness. The plots can have skewness and the median might not be at the center of the box." }, { "code": null, "e": 1351, "s": 1244, "text": "The area inside the box (50% of the data) is known as the Inter Quartile Range. The IQR is calculated as –" }, { "code": null, "e": 1363, "s": 1351, "text": "IQR = Q3-Q1" }, { "code": null, "e": 1481, "s": 1363, "text": "Outliers are the data points below and above the lower and upper limit. The lower and upper limit is calculated as – " }, { "code": null, "e": 1535, "s": 1481, "text": "Lower Limit = Q1 - 1.5*IQR\nUpper Limit = Q3 + 1.5*IQR" }, { "code": null, "e": 1708, "s": 1535, "text": "The values below and above these limits are considered outliers and the minimum and maximum values are calculated from the points which lie under the lower and upper limit." }, { "code": null, "e": 1736, "s": 1708, "text": "2) How to create a box plot" }, { "code": null, "e": 1802, "s": 1736, "text": "Let us take a sample data to understand how to create a box plot." }, { "code": null, "e": 1922, "s": 1802, "text": "Here are the runs scored by a cricket team in a league of 12 matches – 100,120,110,150,110,140,130,170,120,220,140,110." }, { "code": null, "e": 2096, "s": 1922, "text": "To draw a box plot for the given data first we need to arrange the data in ascending order and then find the minimum, first quartile, median, third quartile and the maximum." }, { "code": null, "e": 2229, "s": 2096, "text": "Ascending Order - \n100,110,110,110,120,120,130,140,140,150,170,220\n\nMedian (Q2) = (120+130)/2 = 125 ; Since there were even values" }, { "code": null, "e": 2308, "s": 2229, "text": "To find the First Quartile we take the first six values and find their median." }, { "code": null, "e": 2331, "s": 2308, "text": "Q1 = (110+110)/2 = 110" }, { "code": null, "e": 2399, "s": 2331, "text": "For the Third Quartile, we take the next six and find their median." }, { "code": null, "e": 2422, "s": 2399, "text": "Q3 = (140+150)/2 = 145" }, { "code": null, "e": 2580, "s": 2422, "text": "Note: If the total number of values is odd then we exclude the Median while calculating Q1 and Q3. Here since there were two central values we included them." }, { "code": null, "e": 2632, "s": 2580, "text": "Now, we need to calculate the Inter Quartile Range." }, { "code": null, "e": 2659, "s": 2632, "text": "IQR = Q3-Q1 = 145-110 = 35" }, { "code": null, "e": 2776, "s": 2659, "text": "We can now calculate the Upper and Lower Limits to find the minimum and maximum values and also the outliers if any." }, { "code": null, "e": 2867, "s": 2776, "text": "Lower Limit = Q1-1.5*IQR = 110-1.5*35 = 57.5\nUpper Limit = Q3+1.5*IQR = 145+1.5*35 = 197.5" }, { "code": null, "e": 2951, "s": 2867, "text": "So the minimum and maximum between the range [57.5,197.5] for our given data are – " }, { "code": null, "e": 2979, "s": 2951, "text": "Minimum = 100\nMaximum = 170" }, { "code": null, "e": 3028, "s": 2979, "text": "The outliers which are outside this range are – " }, { "code": null, "e": 3043, "s": 3028, "text": "Outliers = 220" }, { "code": null, "e": 3123, "s": 3043, "text": "Now we have all the information, so we can draw the box plot which is as below-" }, { "code": null, "e": 3275, "s": 3123, "text": "We can see from the diagram that the Median is not exactly at the centre of the box and one whisker is longer than the other. We also have one Outlier." }, { "code": null, "e": 3297, "s": 3275, "text": "3) Uses of a Box Plot" }, { "code": null, "e": 3483, "s": 3297, "text": "Box plots provide a visual summary of the data with which we can quickly identify the average value of the data, how dispersed the data is, whether the data is skewed or not (skewness)." }, { "code": null, "e": 3535, "s": 3483, "text": "The Median gives you the average value of the data." }, { "code": null, "e": 3573, "s": 3535, "text": "Box Plots shows Skewness of the data-" }, { "code": null, "e": 4026, "s": 3573, "text": "a) If the Median is at the center of the Box and the whiskers are almost the \n same on both the ends then the data is Normally Distributed.\nb) If the Median lies closer to the First Quartile and if the whisker at the lower\n end is shorter (as in the above example) then it has a Positive Skew (Right Skew).\nc) If the Median lies closer to the Third Quartile and if the whisker at the\n upper end is shorter then it has a Negative Skew (Left Skew)." }, { "code": null, "e": 4155, "s": 4026, "text": "The dispersion or spread of data can be visualized by the minimum and maximum values which are found at the end of the whiskers." }, { "code": null, "e": 4286, "s": 4155, "text": "The Box plot gives us the idea of about the Outliers which are the points which are numerically distant from the rest of the data." }, { "code": null, "e": 4314, "s": 4286, "text": "4) How to compare box plots" }, { "code": null, "e": 4558, "s": 4314, "text": "As we have discussed at the beginning of the article that box plots make comparing characteristics of data between categories very easy. Let us have a look at how we can compare different box plots and derive statistical conclusions from them." }, { "code": null, "e": 4606, "s": 4558, "text": "Let us take the below two plots as an example:-" }, { "code": null, "e": 4884, "s": 4606, "text": "Compare the Medians — If the median line of a box plot lies outside the box of the other box plot with which it is being compared, then we can say that there is likely to be a difference between the two groups. Here the Median line of the plot B lies outside the box of Plot A." }, { "code": null, "e": 5382, "s": 4884, "text": "Compare the Dispersion or Spread of data — The Inter Quartile range (length of the box) gives us an idea about how dispersed the data is. Here Plot A has a longer length than Plot B which means that the dispersion of data is more in plot A as compared to plot B. The length of whiskers also gives an idea of the overall spread of data. The extreme values (minimum &maximum) gives the range of data distribution. Larger the range more scattered the data. Here Plot A has a larger range than Plot B." }, { "code": null, "e": 5663, "s": 5382, "text": "Comparing Outliers — The outliers gives the idea of unusual data values which are distant from the rest of the data. More number of Outliers means the prediction will be more uncertain. We can be more confident while predicting the values for a plot which has less or no outliers." }, { "code": null, "e": 5886, "s": 5663, "text": "Compare Skewness — Skewness gives us the direction and the magnitude of the lack of symmetry. We have discussed above how to identify skewness. Here Plot A is Positive or Right Skewed and Plot B is Negative or Left Skewed." }, { "code": null, "e": 6063, "s": 5886, "text": "This is all for Box Plots. Now you might have got the idea of Box Plots how to make them and how to derive information from them. For any queries do leave a comment down below." }, { "code": null, "e": 6082, "s": 6063, "text": "Data Visualization" }, { "code": null, "e": 6089, "s": 6082, "text": "ML-EDA" }, { "code": null, "e": 6098, "s": 6089, "text": "ML-plots" }, { "code": null, "e": 6115, "s": 6098, "text": "Machine Learning" }, { "code": null, "e": 6132, "s": 6115, "text": "Machine Learning" }, { "code": null, "e": 6230, "s": 6132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6271, "s": 6230, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 6304, "s": 6271, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 6340, "s": 6304, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 6364, "s": 6340, "text": "Markov Decision Process" }, { "code": null, "e": 6415, "s": 6364, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 6448, "s": 6415, "text": "Normalization vs Standardization" }, { "code": null, "e": 6488, "s": 6448, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 6529, "s": 6488, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 6557, "s": 6529, "text": "Types of Environments in AI" } ]
Python | sympy.zeros() method
29 Jun, 2019 With the help of sympy.zeros() method, we can create a matrix having dimension nxm and filled with zeros by using sympy.zeros() method. Syntax : sympy.zeros()Return : Return a zero matrix. Example #1 :In this example, we can see that by using sympy.zero() method, we are able to create the zero matrix having dimension nxn all filled with zeros, where nxm will be pass as a parameter. # import sympyfrom sympy import * # Use sympy.zero() methodmat = zeros(3, 4) print(mat) Output : Matrix([[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]]) Example #2 : # import sympyfrom sympy import * # Use sympy.zero() methodmat = zeros(2, 4) print(mat) Output : Matrix([[0, 0, 0, 0],[0, 0, 0, 0]]) SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2019" }, { "code": null, "e": 164, "s": 28, "text": "With the help of sympy.zeros() method, we can create a matrix having dimension nxm and filled with zeros by using sympy.zeros() method." }, { "code": null, "e": 217, "s": 164, "text": "Syntax : sympy.zeros()Return : Return a zero matrix." }, { "code": null, "e": 413, "s": 217, "text": "Example #1 :In this example, we can see that by using sympy.zero() method, we are able to create the zero matrix having dimension nxn all filled with zeros, where nxm will be pass as a parameter." }, { "code": "# import sympyfrom sympy import * # Use sympy.zero() methodmat = zeros(3, 4) print(mat)", "e": 504, "s": 413, "text": null }, { "code": null, "e": 513, "s": 504, "text": "Output :" }, { "code": null, "e": 562, "s": 513, "text": "Matrix([[0, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]])" }, { "code": null, "e": 575, "s": 562, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * # Use sympy.zero() methodmat = zeros(2, 4) print(mat)", "e": 666, "s": 575, "text": null }, { "code": null, "e": 675, "s": 666, "text": "Output :" }, { "code": null, "e": 711, "s": 675, "text": "Matrix([[0, 0, 0, 0],[0, 0, 0, 0]])" }, { "code": null, "e": 717, "s": 711, "text": "SymPy" }, { "code": null, "e": 724, "s": 717, "text": "Python" }, { "code": null, "e": 822, "s": 724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 840, "s": 822, "text": "Python Dictionary" }, { "code": null, "e": 882, "s": 840, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 904, "s": 882, "text": "Enumerate() in Python" }, { "code": null, "e": 939, "s": 904, "text": "Read a file line by line in Python" }, { "code": null, "e": 965, "s": 939, "text": "Python String | replace()" }, { "code": null, "e": 997, "s": 965, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1026, "s": 997, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1053, "s": 1026, "text": "Python Classes and Objects" }, { "code": null, "e": 1083, "s": 1053, "text": "Iterate over a list in Python" } ]
GATE CS 2011 - GeeksforGeeks
11 Oct, 2021 A layer-4 firewall (a device that can look at all protocol headers up to the transport layer) CANNOT block entire HTTP traffic during 9:00PM and 5 :0OAM block all ICMP traffic stop incoming traffic from a specific IP address but allow outgoing traffic to the same IP address block TCP traffic from a specific user on a multi-user system during 9:00PM and 5:00AM A.Can Block entire HTTP traffic by blocking TCP port 80 and it is possible because it is L4 firewall. D) As it is L4 firewall can not block packets based on user identity because it is the responsibility of Application layer m1: Send an email from a mail client to a mail server m2: Download an email from mailbox server to a mail client m3: Checking email in a web browser Effort Applied (E) = ab(KLOC)bb [ person-months ] = 2.8 x(40)1.20 = 2.8 x 83.65 = 234.25 NDPDA can handle languages or grammars with ambiguity, but DPDA cannot handle languages with ambiguity and any context-free grammar. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Java Threads Top 20 Puzzles Commonly Asked During SDE Interviews Software Testing Metrics, its Types and Example Software Testing - Test Plan Software Testing - Boundary Value Analysis TCS NQT Coding Sheet
[ { "code": null, "e": 29577, "s": 29549, "text": "\n11 Oct, 2021" }, { "code": null, "e": 29679, "s": 29577, "text": "A layer-4 firewall (a device that can look at all protocol headers up to the transport layer) CANNOT " }, { "code": null, "e": 29732, "s": 29679, "text": "block entire HTTP traffic during 9:00PM and 5 :0OAM " }, { "code": null, "e": 29756, "s": 29732, "text": "block all ICMP traffic " }, { "code": null, "e": 29856, "s": 29756, "text": "stop incoming traffic from a specific IP address but allow outgoing traffic to the same IP address " }, { "code": null, "e": 29944, "s": 29856, "text": "block TCP traffic from a specific user on a multi-user system during 9:00PM and 5:00AM " }, { "code": null, "e": 30170, "s": 29944, "text": "A.Can Block entire HTTP traffic by blocking TCP port 80 and it is possible because it is L4 firewall. D) As it is L4 firewall can not block packets based on user identity because it is the responsibility of Application layer " }, { "code": null, "e": 30319, "s": 30170, "text": "m1: Send an email from a mail client to a mail server\nm2: Download an email from mailbox server to a mail client\nm3: Checking email in a web browser" }, { "code": null, "e": 30468, "s": 30319, "text": "Effort Applied (E) = ab(KLOC)bb [ person-months ]\n = 2.8 x(40)1.20 \n = 2.8 x 83.65 \n = 234.25 " }, { "code": null, "e": 30601, "s": 30468, "text": "NDPDA can handle languages or grammars with ambiguity, but DPDA cannot handle languages with ambiguity and any context-free grammar." }, { "code": null, "e": 30699, "s": 30601, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 30773, "s": 30699, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 30826, "s": 30773, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 30875, "s": 30826, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30900, "s": 30875, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30913, "s": 30900, "text": "Java Threads" }, { "code": null, "e": 30965, "s": 30913, "text": "Top 20 Puzzles Commonly Asked During SDE Interviews" }, { "code": null, "e": 31013, "s": 30965, "text": "Software Testing Metrics, its Types and Example" }, { "code": null, "e": 31042, "s": 31013, "text": "Software Testing - Test Plan" }, { "code": null, "e": 31085, "s": 31042, "text": "Software Testing - Boundary Value Analysis" } ]
Count of elements which form a loop in an Array according to given constraints
15 Jun, 2021 Given an array A containing N integers, the task is to count the number of elements which form a cycle in the array, based on the following condition. Start to traverse the Array from index i and jump to its next connected index. A directed edge exits from index i of A to index j if j = GCD(i, A[i]) % N. If on traversing array in the described order, index i is again visited then index i is said to form a cycle in an array. Examples: Input: A = { 1, 1, 6, 2 } Output: 2 Explanation: Possible traversals with the given condition are: 0 -> 1 -> 1 1 -> 1 2 -> 2 3 -> 2 -> 2 Clearly, only vertices 1 and 2 forms a cycle.Input: A = {0, 0, 0, 6} Output: 4 Explanation: Possible traversals with the given condition are: 0 -> 0 1 -> 1 2 -> 2 3 -> 3 Clearly, all the vertices forms a cycle. Approach: To solve the problem mentioned above, we have to assume that each index represents a single node of the graph. Each node has a single directed edge from index i of A to index j if j = GCD(i, A[i]) % n. If the traversal begins from node i. Node i will be called parent node of this traversal and this parent node will be assigned to all the nodes visited during traversal. While traversing the graph if we discover a node that is already visited and parent node of that visited node is same as parent node of the traversal then a new cycle is detected. Now, every node in this cycle will be counted as each of them is forming the cycle. To count number of nodes in this cycle, start another DFS from this node until this same node is not visited again. This procedure is repeated for every node i of the graph. In the worst case, every node will be traversed at most 3 times. Hence solution has linear time complexity.Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to number of elements// which form a cycle in an array #include <bits/stdc++.h>using namespace std; #define mp make_pair#define pb push_back#define mod 1000000007 // Function to count number of// elements forming a cycleint solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int parent[n]; // Array to determine // whether current node // is already counted // in the cycle. int vis[n]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} int main(){ int A[] = { 1, 1, 6, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0;} // Java program to number of elements// which form a cycle in an arrayimport java.util.*;class GFG{ static final int mod = 1000000007; // Function to count number of// elements forming a cyclestatic int solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int []parent = new int[n]; // Array to determine // whether current node // is already counted // in the cycle. int []vis = new int[n]; // Initialize the arrays. Arrays.fill(parent, -1); Arrays.fill(vis, 0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int A[] = { 1, 1, 6, 2 }; int n = A.length; System.out.print(solve(A, n));}} // This code is contributed by gauravrajput1 # Python3 program to number of elements# which form a cycle in an arrayimport math mod = 1000000007 # Function to count number of# elements forming a cycledef solve(A, n): cnt = 0 # Array to store parent # node of traversal. parent = [-1] * n # Array to determine # whether current node # is already counted # in the cycle. vis = [0] * n for i in range(n): j = i # Check if current node is already # traversed or not. If node is not # traversed yet then parent value # will be -1. if (parent[j] == -1): # Traverse the graph until an # already visited node is not # found. while (parent[j] == -1): parent[j] = i j = math.gcd(j, A[j]) % n # Check parent value to ensure # a cycle is present. if (parent[j] == i): # Count number of nodes in # the cycle. while (vis[j] == 0): vis[j] = 1 cnt += 1 j = math.gcd(j, A[j]) % n return cnt # Driver codeA = [ 1, 1, 6, 2 ]n = len(A) print(solve(A, n)) # This code is contributed by sanjoy_62 // C# program to number of elements// which form a cycle in an arrayusing System; class GFG{ // Function to count number of// elements forming a cyclestatic int solve(int[] A, int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int[] parent = new int[n]; // Array to determine // whether current node // is already counted // in the cycle. int[] vis = new int[n]; // Initialize the arrays. Array.Fill(parent, -1); Array.Fill(vis, 0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codestatic void Main(){ int[] A = { 1, 1, 6, 2 }; int n = A.Length; Console.WriteLine(solve(A, n));}} // This code is contributed by divyeshrabadiya07 <script> // JavaScript program to number of elements // which form a cycle in an array // Function to count number of // elements forming a cycle function solve(A, n) { let i, cnt = 0, j; // Array to store parent // node of traversal. let parent = new Array(n); // Array to determine // whether current node // is already counted // in the cycle. let vis = new Array(n); // Initialize the arrays. parent.fill(-1); vis.fill(0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt; } function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } let A = [ 1, 1, 6, 2 ]; let n = A.length; document.write(solve(A, n)); </script> 2 Time Complexity: O(N)Space Complexity: O(N) GauravRajput1 Rohit_ranjan sanjoy_62 divyeshrabadiya07 mukesh07 DFS graph-cycle Analysis Arrays Competitive Programming Write From Home Arrays DFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2021" }, { "code": null, "e": 492, "s": 54, "text": "Given an array A containing N integers, the task is to count the number of elements which form a cycle in the array, based on the following condition. Start to traverse the Array from index i and jump to its next connected index. A directed edge exits from index i of A to index j if j = GCD(i, A[i]) % N. If on traversing array in the described order, index i is again visited then index i is said to form a cycle in an array. Examples:" }, { "code": null, "e": 840, "s": 492, "text": "Input: A = { 1, 1, 6, 2 } Output: 2 Explanation: Possible traversals with the given condition are: 0 -> 1 -> 1 1 -> 1 2 -> 2 3 -> 2 -> 2 Clearly, only vertices 1 and 2 forms a cycle.Input: A = {0, 0, 0, 6} Output: 4 Explanation: Possible traversals with the given condition are: 0 -> 0 1 -> 1 2 -> 2 3 -> 3 Clearly, all the vertices forms a cycle." }, { "code": null, "e": 961, "s": 840, "text": "Approach: To solve the problem mentioned above, we have to assume that each index represents a single node of the graph." }, { "code": null, "e": 1089, "s": 961, "text": "Each node has a single directed edge from index i of A to index j if j = GCD(i, A[i]) % n. If the traversal begins from node i." }, { "code": null, "e": 1222, "s": 1089, "text": "Node i will be called parent node of this traversal and this parent node will be assigned to all the nodes visited during traversal." }, { "code": null, "e": 1402, "s": 1222, "text": "While traversing the graph if we discover a node that is already visited and parent node of that visited node is same as parent node of the traversal then a new cycle is detected." }, { "code": null, "e": 1602, "s": 1402, "text": "Now, every node in this cycle will be counted as each of them is forming the cycle. To count number of nodes in this cycle, start another DFS from this node until this same node is not visited again." }, { "code": null, "e": 1660, "s": 1602, "text": "This procedure is repeated for every node i of the graph." }, { "code": null, "e": 1814, "s": 1660, "text": "In the worst case, every node will be traversed at most 3 times. Hence solution has linear time complexity.Below is the implementation of above approach:" }, { "code": null, "e": 1818, "s": 1814, "text": "C++" }, { "code": null, "e": 1823, "s": 1818, "text": "Java" }, { "code": null, "e": 1831, "s": 1823, "text": "Python3" }, { "code": null, "e": 1834, "s": 1831, "text": "C#" }, { "code": null, "e": 1845, "s": 1834, "text": "Javascript" }, { "code": "// C++ program to number of elements// which form a cycle in an array #include <bits/stdc++.h>using namespace std; #define mp make_pair#define pb push_back#define mod 1000000007 // Function to count number of// elements forming a cycleint solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int parent[n]; // Array to determine // whether current node // is already counted // in the cycle. int vis[n]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} int main(){ int A[] = { 1, 1, 6, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0;}", "e": 3359, "s": 1845, "text": null }, { "code": "// Java program to number of elements// which form a cycle in an arrayimport java.util.*;class GFG{ static final int mod = 1000000007; // Function to count number of// elements forming a cyclestatic int solve(int A[], int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int []parent = new int[n]; // Array to determine // whether current node // is already counted // in the cycle. int []vis = new int[n]; // Initialize the arrays. Arrays.fill(parent, -1); Arrays.fill(vis, 0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codepublic static void main(String[] args){ int A[] = { 1, 1, 6, 2 }; int n = A.length; System.out.print(solve(A, n));}} // This code is contributed by gauravrajput1", "e": 5042, "s": 3359, "text": null }, { "code": "# Python3 program to number of elements# which form a cycle in an arrayimport math mod = 1000000007 # Function to count number of# elements forming a cycledef solve(A, n): cnt = 0 # Array to store parent # node of traversal. parent = [-1] * n # Array to determine # whether current node # is already counted # in the cycle. vis = [0] * n for i in range(n): j = i # Check if current node is already # traversed or not. If node is not # traversed yet then parent value # will be -1. if (parent[j] == -1): # Traverse the graph until an # already visited node is not # found. while (parent[j] == -1): parent[j] = i j = math.gcd(j, A[j]) % n # Check parent value to ensure # a cycle is present. if (parent[j] == i): # Count number of nodes in # the cycle. while (vis[j] == 0): vis[j] = 1 cnt += 1 j = math.gcd(j, A[j]) % n return cnt # Driver codeA = [ 1, 1, 6, 2 ]n = len(A) print(solve(A, n)) # This code is contributed by sanjoy_62", "e": 6301, "s": 5042, "text": null }, { "code": "// C# program to number of elements// which form a cycle in an arrayusing System; class GFG{ // Function to count number of// elements forming a cyclestatic int solve(int[] A, int n){ int i, cnt = 0, j; // Array to store parent // node of traversal. int[] parent = new int[n]; // Array to determine // whether current node // is already counted // in the cycle. int[] vis = new int[n]; // Initialize the arrays. Array.Fill(parent, -1); Array.Fill(vis, 0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt;} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codestatic void Main(){ int[] A = { 1, 1, 6, 2 }; int n = A.Length; Console.WriteLine(solve(A, n));}} // This code is contributed by divyeshrabadiya07", "e": 7941, "s": 6301, "text": null }, { "code": "<script> // JavaScript program to number of elements // which form a cycle in an array // Function to count number of // elements forming a cycle function solve(A, n) { let i, cnt = 0, j; // Array to store parent // node of traversal. let parent = new Array(n); // Array to determine // whether current node // is already counted // in the cycle. let vis = new Array(n); // Initialize the arrays. parent.fill(-1); vis.fill(0); for(i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = __gcd(j, A[j]) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (vis[j] == 0) { vis[j] = 1; cnt++; j = __gcd(j, A[j]) % n; } } } } return cnt; } function __gcd(a, b) { return b == 0 ? a : __gcd(b, a % b); } let A = [ 1, 1, 6, 2 ]; let n = A.length; document.write(solve(A, n)); </script>", "e": 9677, "s": 7941, "text": null }, { "code": null, "e": 9679, "s": 9677, "text": "2" }, { "code": null, "e": 9724, "s": 9679, "text": "Time Complexity: O(N)Space Complexity: O(N) " }, { "code": null, "e": 9738, "s": 9724, "text": "GauravRajput1" }, { "code": null, "e": 9751, "s": 9738, "text": "Rohit_ranjan" }, { "code": null, "e": 9761, "s": 9751, "text": "sanjoy_62" }, { "code": null, "e": 9779, "s": 9761, "text": "divyeshrabadiya07" }, { "code": null, "e": 9788, "s": 9779, "text": "mukesh07" }, { "code": null, "e": 9792, "s": 9788, "text": "DFS" }, { "code": null, "e": 9804, "s": 9792, "text": "graph-cycle" }, { "code": null, "e": 9813, "s": 9804, "text": "Analysis" }, { "code": null, "e": 9820, "s": 9813, "text": "Arrays" }, { "code": null, "e": 9844, "s": 9820, "text": "Competitive Programming" }, { "code": null, "e": 9860, "s": 9844, "text": "Write From Home" }, { "code": null, "e": 9867, "s": 9860, "text": "Arrays" }, { "code": null, "e": 9871, "s": 9867, "text": "DFS" } ]
Tensors in Pytorch
04 Jul, 2021 A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation. However, the biggest difference between a NumPy array and a PyTorch Tensor is that a PyTorch Tensor can run on either CPU or GPU. To run operations on the GPU, just cast the Tensor to a cuda datatype using: device = torch.device(“cpu”) # to create random input and output data , # and H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 32, 100, 10, 2 x = torch.randn(N, D_in, device=device, dtype=torch.float) #where x is a tensor In the above example, x can be thought of as a random feature tensor as an input to a model. We will see how to create tensors, different attributes, and operations on a tensor in this article. You can create a tensor using some simple lines of code as shown below. Python3 import torchV_data = [1, 2, 3, 4, 5]V = torch.tensor(V_data)print(V) Output: tensor([1, 2, 3, 4, 5]) You can also create a tensor of random data with a given dimensionality like: Python3 import torch x = torch.randn((3, 4, 5))print(x) Output : tensor([[[ 0.8332, -0.2102, 0.0213, 0.4375, -0.9506], [ 0.0877, -1.5845, -0.1520, 0.3944, -0.7282], [-0.6923, 0.0332, -0.4628, -0.9127, -1.4349], [-0.3641, -0.5880, -0.5963, -1.4126, 0.5308]], [[ 0.4492, -1.2030, 2.5985, 0.8966, 0.4876], [ 0.5083, 1.4515, 0.6496, 0.3407, 0.0093], [ 0.1237, 0.3783, -0.7969, 1.4019, 0.0633], [ 0.4399, 0.3827, 1.2231, -0.0674, -1.0158]], [[-0.2490, -0.5475, 0.6201, -2.2092, 0.8405], [ 0.1684, -1.0118, 0.7414, -3.3518, -0.3209], [ 0.6543, 0.1956, -0.2954, 0.1055, 1.6523], [-0.9872, -2.0118, -1.6609, 1.4072, 0.0632]]]) You can also create tensors using the following functions: torch.zeros(): Creates a new Tensor with all elements, initialized as zeros. Python3 import torch z= torch.zeros([3,3], dtype=torch.int32)print(z) Output: tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]], dtype=torch.int32) torch.ones(): Creates a new Tensor with all elements, initialized as ones. Python3 import torch z = torch.ones([3,3])print(z) Output: tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]) torch.full() and torch.full_like(): These functions return a Tensor of the required size filled with required fill_value provided. The complete prototype for torch.full() is: Syntax: torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) And torch.full_like() is: Syntax: torch.full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format) Python3 import torch # example of torch.full()newTensor= torch.full((4, 3), 3.14,dtype= torch.float32)print(newTensor) Output: tensor([[3.1400, 3.1400, 3.1400], [3.1400, 3.1400, 3.1400], [3.1400, 3.1400, 3.1400], [3.1400, 3.1400, 3.1400]]) Python3 import torch # Example for torch.full_like()x = torch.full_like(newTensor,3.24, dtype=None )print(x) Output: tensor([[3.2400, 3.2400, 3.2400], [3.2400, 3.2400, 3.2400], [3.2400, 3.2400, 3.2400], [3.2400, 3.2400, 3.2400]]) Here a new Tensor is returned, with the same size and dtype as the newTensor which was earlier returned from the torch.full method in the example shown above. Each tensor( torch.Tensor ) has a torch.dtype, torch.device, and torch.layout attributes. torch.dtype: A torch.dtype is an object that represents the data type of torch.Tensor. PyTorch has twelve different data types. torch.device: A torch.device is an object representing the device on which a torch.Tensor is or will be allocated. The torch.device contains a device type (‘cpu’ or ‘cuda’) and an optional device ordinal for the device type. Example: Python3 torch.device('cuda:0') Output : device(type='cuda', index=0) If the device ordinal is not present, this object will always represent the current device for the device type, even after torch.cuda.set_device() is called. torch.layout: A torch.layout is an object that represents the memory layout of a torch.Tensor. Currently, the torch supports two types of memory layout. 1. torch.strided: Represents dense Tensors and is the memory layout that is most commonly used. Each stridden tensor has an associated torch.Storage, which holds its data. These tensors provide a multi-dimensional, stridden view of storage. The stride of an array (also referred to as increment, pitch or step size) is the number of locations in memory between the beginnings of successive array elements, measured in bytes or in units of the size of the array’s elements. The stride cannot be smaller than the element size but can be larger, indicating extra space between elements. So basically here Strides are a list of integers: the k-th stride represents the jump in the memory necessary to go from one element to the next one in the kth dimension of the Tensor. This concept makes it possible to perform many tensor operations efficiently. Let’s run some example snippets: Python3 x = torch.Tensor([[1, 2, 3, 4], [5, 7, 8, 9]])x.stride() Output: (4,1) 2. torch.sparse_coo_tensor: Used to store array in the sparse coordinate list. In COO format, the specified elements are stored as tuples of element indices and the corresponding values. Python3 i = [[0, 1, 1], [2, 0, 2]] v = [3, 4, 5]s = torch.sparse_coo_tensor(i, v, (2, 3))Print(s) Output: tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3, 4, 5]), size=(2, 3), nnz=3, layout=torch.sparse_coo) You can add two tensors like matrix addition. Python3 x = torch.tensor([1., 2., 3.])y = torch.tensor([4., 5., 6.])z = x + yprint(z) Output: tensor([5., 7., 9.]) torch.cat() : Concatenates a list of tensors Python3 x_1 = torch.randn(2, 5)y_1 = torch.randn(3, 5)z_1 = torch.cat([x_1, y_1])print(z_1) Output: tensor([[ 0.5761, 0.6781, 0.1621, 0.4986, 0.3410], [-0.8428, 0.2510, -0.2668, -1.1475, 0.5675], [-0.2797, -0.0699, 2.8936, 1.8260, 2.1227], [ 1.3765, -0.0939, -0.3774, -0.3834, 0.0682], [ 2.3666, 0.0904, 0.7956, 1.2281, 0.5561]]) To concatenate columns you can do the following. Python3 x_2 = torch.randn(2, 3)y_2 = torch.randn(2, 5) # second argument specifies which axis to concat alongz_2 = torch.cat([x_2, y_2], 1)print(z_2) Output: tensor([[ 0.5818, 0.7047, 0.1581, 1.8658, 0.5953, -0.9453, -0.6395, -0.7106], [ 1.2197, 0.8110, -1.6072, 0.1463, 0.4895, -0.8226, -0.1889, 0.2668]]) view(): You can reshape tensors using the .view() method as shown below. Python3 x = torch.randn(2, 3, 4)print(x) # reshape to 2 rows, 12 columnsprint(x.view(2, 12)) Output: tensor([[[ 0.4321, 0.2414, -0.4776, 1.6408], [ 0.9085, 0.9195, 0.1321, 1.1891], [-0.9267, -0.1384, 0.0115, -0.4731]], [[ 0.7256, 0.6990, -1.7374, 0.6053], [ 0.0224, -1.2108, 0.1974, 0.0655], [-0.6182, -0.0797, 0.2603, -1.3280]]]) tensor([[ 0.4321, 0.2414, -0.4776, 1.6408, 0.9085, 0.9195, 0.1321, 1.1891, -0.9267, -0.1384, 0.0115, -0.4731], [ 0.7256, 0.6990, -1.7374, 0.6053, 0.0224, -1.2108, 0.1974, 0.0655, -0.6182, -0.0797, 0.2603, -1.3280]]) torch.argmax(): Returns the index of the maximum value of all elements in the input tensor. Python3 x = torch.randn(3,3)print((x, torch.argmax(x))) Output: (tensor([[ 1.9610, -0.7683, -2.6080], [-0.3659, -0.1731, 0.1061], [ 0.8582, 0.6420, -0.2380]]), tensor(0)) torch.argmin(): Similar to argmax(), it returns the minimum value of all elements in the input tensor. Python3 x = torch.randn(3,3)print((x, torch.argmin(x))) Output: (tensor([[ 0.9838, -1.2761, 0.2257], [-0.4754, 1.2677, 1.1973], [-1.2298, -0.5710, -1.3635]]), tensor(8)) Picked Python-PyTorch Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 474, "s": 28, "text": "A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation. However, the biggest difference between a NumPy array and a PyTorch Tensor is that a PyTorch Tensor can run on either CPU or GPU. To run operations on the GPU, just cast the Tensor to a cuda datatype using:" }, { "code": null, "e": 503, "s": 474, "text": "device = torch.device(“cpu”)" }, { "code": null, "e": 546, "s": 503, "text": "# to create random input and output data ," }, { "code": null, "e": 602, "s": 546, "text": "# and H is hidden dimension; D_out is output dimension." }, { "code": null, "e": 638, "s": 602, "text": "N, D_in, H, D_out = 32, 100, 10, 2 " }, { "code": null, "e": 722, "s": 638, "text": "x = torch.randn(N, D_in, device=device, dtype=torch.float) #where x is a tensor " }, { "code": null, "e": 916, "s": 722, "text": "In the above example, x can be thought of as a random feature tensor as an input to a model. We will see how to create tensors, different attributes, and operations on a tensor in this article." }, { "code": null, "e": 988, "s": 916, "text": "You can create a tensor using some simple lines of code as shown below." }, { "code": null, "e": 996, "s": 988, "text": "Python3" }, { "code": "import torchV_data = [1, 2, 3, 4, 5]V = torch.tensor(V_data)print(V)", "e": 1065, "s": 996, "text": null }, { "code": null, "e": 1074, "s": 1065, "text": "Output: " }, { "code": null, "e": 1098, "s": 1074, "text": "tensor([1, 2, 3, 4, 5])" }, { "code": null, "e": 1176, "s": 1098, "text": "You can also create a tensor of random data with a given dimensionality like:" }, { "code": null, "e": 1184, "s": 1176, "text": "Python3" }, { "code": "import torch x = torch.randn((3, 4, 5))print(x)", "e": 1233, "s": 1184, "text": null }, { "code": null, "e": 1242, "s": 1233, "text": "Output :" }, { "code": null, "e": 1920, "s": 1242, "text": "tensor([[[ 0.8332, -0.2102, 0.0213, 0.4375, -0.9506],\n [ 0.0877, -1.5845, -0.1520, 0.3944, -0.7282],\n [-0.6923, 0.0332, -0.4628, -0.9127, -1.4349],\n [-0.3641, -0.5880, -0.5963, -1.4126, 0.5308]],\n\n [[ 0.4492, -1.2030, 2.5985, 0.8966, 0.4876],\n [ 0.5083, 1.4515, 0.6496, 0.3407, 0.0093],\n [ 0.1237, 0.3783, -0.7969, 1.4019, 0.0633],\n [ 0.4399, 0.3827, 1.2231, -0.0674, -1.0158]],\n\n [[-0.2490, -0.5475, 0.6201, -2.2092, 0.8405],\n [ 0.1684, -1.0118, 0.7414, -3.3518, -0.3209],\n [ 0.6543, 0.1956, -0.2954, 0.1055, 1.6523],\n [-0.9872, -2.0118, -1.6609, 1.4072, 0.0632]]])" }, { "code": null, "e": 1979, "s": 1920, "text": "You can also create tensors using the following functions:" }, { "code": null, "e": 2056, "s": 1979, "text": "torch.zeros(): Creates a new Tensor with all elements, initialized as zeros." }, { "code": null, "e": 2064, "s": 2056, "text": "Python3" }, { "code": "import torch z= torch.zeros([3,3], dtype=torch.int32)print(z)", "e": 2127, "s": 2064, "text": null }, { "code": null, "e": 2137, "s": 2127, "text": "Output: " }, { "code": null, "e": 2214, "s": 2137, "text": "tensor([[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]], dtype=torch.int32)" }, { "code": null, "e": 2290, "s": 2214, "text": "torch.ones(): Creates a new Tensor with all elements, initialized as ones." }, { "code": null, "e": 2298, "s": 2290, "text": "Python3" }, { "code": "import torch z = torch.ones([3,3])print(z)", "e": 2342, "s": 2298, "text": null }, { "code": null, "e": 2350, "s": 2342, "text": "Output:" }, { "code": null, "e": 2417, "s": 2350, "text": "tensor([[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]])" }, { "code": null, "e": 2593, "s": 2417, "text": "torch.full() and torch.full_like(): These functions return a Tensor of the required size filled with required fill_value provided. The complete prototype for torch.full() is:" }, { "code": null, "e": 2708, "s": 2593, "text": "Syntax: torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)" }, { "code": null, "e": 2734, "s": 2708, "text": "And torch.full_like() is:" }, { "code": null, "e": 2892, "s": 2734, "text": "Syntax: torch.full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, memory_format=torch.preserve_format)" }, { "code": null, "e": 2900, "s": 2892, "text": "Python3" }, { "code": "import torch # example of torch.full()newTensor= torch.full((4, 3), 3.14,dtype= torch.float32)print(newTensor)", "e": 3012, "s": 2900, "text": null }, { "code": null, "e": 3020, "s": 3012, "text": "Output:" }, { "code": null, "e": 3157, "s": 3020, "text": "tensor([[3.1400, 3.1400, 3.1400],\n [3.1400, 3.1400, 3.1400],\n [3.1400, 3.1400, 3.1400],\n [3.1400, 3.1400, 3.1400]])" }, { "code": null, "e": 3165, "s": 3157, "text": "Python3" }, { "code": "import torch # Example for torch.full_like()x = torch.full_like(newTensor,3.24, dtype=None )print(x)", "e": 3267, "s": 3165, "text": null }, { "code": null, "e": 3276, "s": 3267, "text": "Output: " }, { "code": null, "e": 3413, "s": 3276, "text": "tensor([[3.2400, 3.2400, 3.2400],\n [3.2400, 3.2400, 3.2400],\n [3.2400, 3.2400, 3.2400],\n [3.2400, 3.2400, 3.2400]])" }, { "code": null, "e": 3572, "s": 3413, "text": "Here a new Tensor is returned, with the same size and dtype as the newTensor which was earlier returned from the torch.full method in the example shown above." }, { "code": null, "e": 3663, "s": 3572, "text": "Each tensor( torch.Tensor ) has a torch.dtype, torch.device, and torch.layout attributes. " }, { "code": null, "e": 3791, "s": 3663, "text": "torch.dtype: A torch.dtype is an object that represents the data type of torch.Tensor. PyTorch has twelve different data types." }, { "code": null, "e": 4016, "s": 3791, "text": "torch.device: A torch.device is an object representing the device on which a torch.Tensor is or will be allocated. The torch.device contains a device type (‘cpu’ or ‘cuda’) and an optional device ordinal for the device type." }, { "code": null, "e": 4025, "s": 4016, "text": "Example:" }, { "code": null, "e": 4033, "s": 4025, "text": "Python3" }, { "code": "torch.device('cuda:0')", "e": 4056, "s": 4033, "text": null }, { "code": null, "e": 4066, "s": 4056, "text": "Output : " }, { "code": null, "e": 4095, "s": 4066, "text": "device(type='cuda', index=0)" }, { "code": null, "e": 4253, "s": 4095, "text": "If the device ordinal is not present, this object will always represent the current device for the device type, even after torch.cuda.set_device() is called." }, { "code": null, "e": 4406, "s": 4253, "text": "torch.layout: A torch.layout is an object that represents the memory layout of a torch.Tensor. Currently, the torch supports two types of memory layout." }, { "code": null, "e": 5253, "s": 4406, "text": "1. torch.strided: Represents dense Tensors and is the memory layout that is most commonly used. Each stridden tensor has an associated torch.Storage, which holds its data. These tensors provide a multi-dimensional, stridden view of storage. The stride of an array (also referred to as increment, pitch or step size) is the number of locations in memory between the beginnings of successive array elements, measured in bytes or in units of the size of the array’s elements. The stride cannot be smaller than the element size but can be larger, indicating extra space between elements. So basically here Strides are a list of integers: the k-th stride represents the jump in the memory necessary to go from one element to the next one in the kth dimension of the Tensor. This concept makes it possible to perform many tensor operations efficiently." }, { "code": null, "e": 5286, "s": 5253, "text": "Let’s run some example snippets:" }, { "code": null, "e": 5294, "s": 5286, "text": "Python3" }, { "code": "x = torch.Tensor([[1, 2, 3, 4], [5, 7, 8, 9]])x.stride()", "e": 5351, "s": 5294, "text": null }, { "code": null, "e": 5359, "s": 5351, "text": "Output:" }, { "code": null, "e": 5365, "s": 5359, "text": "(4,1)" }, { "code": null, "e": 5553, "s": 5365, "text": "2. torch.sparse_coo_tensor: Used to store array in the sparse coordinate list. In COO format, the specified elements are stored as tuples of element indices and the corresponding values. " }, { "code": null, "e": 5561, "s": 5553, "text": "Python3" }, { "code": "i = [[0, 1, 1], [2, 0, 2]] v = [3, 4, 5]s = torch.sparse_coo_tensor(i, v, (2, 3))Print(s)", "e": 5657, "s": 5561, "text": null }, { "code": null, "e": 5666, "s": 5657, "text": "Output: " }, { "code": null, "e": 5821, "s": 5666, "text": "tensor(indices=tensor([[0, 1, 1],\n [2, 0, 2]]),\n values=tensor([3, 4, 5]),\n size=(2, 3), nnz=3, layout=torch.sparse_coo)" }, { "code": null, "e": 5867, "s": 5821, "text": "You can add two tensors like matrix addition." }, { "code": null, "e": 5875, "s": 5867, "text": "Python3" }, { "code": "x = torch.tensor([1., 2., 3.])y = torch.tensor([4., 5., 6.])z = x + yprint(z)", "e": 5953, "s": 5875, "text": null }, { "code": null, "e": 5962, "s": 5953, "text": "Output: " }, { "code": null, "e": 5983, "s": 5962, "text": "tensor([5., 7., 9.])" }, { "code": null, "e": 6028, "s": 5983, "text": "torch.cat() : Concatenates a list of tensors" }, { "code": null, "e": 6036, "s": 6028, "text": "Python3" }, { "code": "x_1 = torch.randn(2, 5)y_1 = torch.randn(3, 5)z_1 = torch.cat([x_1, y_1])print(z_1)", "e": 6120, "s": 6036, "text": null }, { "code": null, "e": 6129, "s": 6120, "text": "Output: " }, { "code": null, "e": 6405, "s": 6129, "text": "tensor([[ 0.5761, 0.6781, 0.1621, 0.4986, 0.3410],\n [-0.8428, 0.2510, -0.2668, -1.1475, 0.5675],\n [-0.2797, -0.0699, 2.8936, 1.8260, 2.1227],\n [ 1.3765, -0.0939, -0.3774, -0.3834, 0.0682],\n [ 2.3666, 0.0904, 0.7956, 1.2281, 0.5561]])" }, { "code": null, "e": 6454, "s": 6405, "text": "To concatenate columns you can do the following." }, { "code": null, "e": 6462, "s": 6454, "text": "Python3" }, { "code": "x_2 = torch.randn(2, 3)y_2 = torch.randn(2, 5) # second argument specifies which axis to concat alongz_2 = torch.cat([x_2, y_2], 1)print(z_2)", "e": 6605, "s": 6462, "text": null }, { "code": null, "e": 6613, "s": 6605, "text": "Output:" }, { "code": null, "e": 6778, "s": 6613, "text": "tensor([[ 0.5818, 0.7047, 0.1581, 1.8658, 0.5953, -0.9453, -0.6395, -0.7106],\n [ 1.2197, 0.8110, -1.6072, 0.1463, 0.4895, -0.8226, -0.1889, 0.2668]])" }, { "code": null, "e": 6851, "s": 6778, "text": "view(): You can reshape tensors using the .view() method as shown below." }, { "code": null, "e": 6859, "s": 6851, "text": "Python3" }, { "code": "x = torch.randn(2, 3, 4)print(x) # reshape to 2 rows, 12 columnsprint(x.view(2, 12))", "e": 6945, "s": 6859, "text": null }, { "code": null, "e": 6953, "s": 6945, "text": "Output:" }, { "code": null, "e": 7494, "s": 6953, "text": "tensor([[[ 0.4321, 0.2414, -0.4776, 1.6408],\n [ 0.9085, 0.9195, 0.1321, 1.1891],\n [-0.9267, -0.1384, 0.0115, -0.4731]],\n\n [[ 0.7256, 0.6990, -1.7374, 0.6053],\n [ 0.0224, -1.2108, 0.1974, 0.0655],\n [-0.6182, -0.0797, 0.2603, -1.3280]]])\ntensor([[ 0.4321, 0.2414, -0.4776, 1.6408, 0.9085, 0.9195, 0.1321, 1.1891,\n -0.9267, -0.1384, 0.0115, -0.4731],\n [ 0.7256, 0.6990, -1.7374, 0.6053, 0.0224, -1.2108, 0.1974, 0.0655,\n -0.6182, -0.0797, 0.2603, -1.3280]])" }, { "code": null, "e": 7586, "s": 7494, "text": "torch.argmax(): Returns the index of the maximum value of all elements in the input tensor." }, { "code": null, "e": 7594, "s": 7586, "text": "Python3" }, { "code": "x = torch.randn(3,3)print((x, torch.argmax(x)))", "e": 7642, "s": 7594, "text": null }, { "code": null, "e": 7651, "s": 7642, "text": "Output: " }, { "code": null, "e": 7776, "s": 7651, "text": "(tensor([[ 1.9610, -0.7683, -2.6080],\n [-0.3659, -0.1731, 0.1061],\n [ 0.8582, 0.6420, -0.2380]]), tensor(0))" }, { "code": null, "e": 7879, "s": 7776, "text": "torch.argmin(): Similar to argmax(), it returns the minimum value of all elements in the input tensor." }, { "code": null, "e": 7887, "s": 7879, "text": "Python3" }, { "code": "x = torch.randn(3,3)print((x, torch.argmin(x)))", "e": 7935, "s": 7887, "text": null }, { "code": null, "e": 7944, "s": 7935, "text": "Output: " }, { "code": null, "e": 8069, "s": 7944, "text": "(tensor([[ 0.9838, -1.2761, 0.2257],\n [-0.4754, 1.2677, 1.1973],\n [-1.2298, -0.5710, -1.3635]]), tensor(8))" }, { "code": null, "e": 8076, "s": 8069, "text": "Picked" }, { "code": null, "e": 8091, "s": 8076, "text": "Python-PyTorch" }, { "code": null, "e": 8098, "s": 8091, "text": "Python" }, { "code": null, "e": 8196, "s": 8098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8228, "s": 8196, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8255, "s": 8228, "text": "Python Classes and Objects" }, { "code": null, "e": 8276, "s": 8255, "text": "Python OOPs Concepts" }, { "code": null, "e": 8299, "s": 8276, "text": "Introduction To PYTHON" }, { "code": null, "e": 8355, "s": 8299, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 8386, "s": 8355, "text": "Python | os.path.join() method" }, { "code": null, "e": 8428, "s": 8386, "text": "Check if element exists in list in Python" }, { "code": null, "e": 8470, "s": 8428, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 8509, "s": 8470, "text": "Python | Get unique values from a list" } ]
How to Count the Number of Repeated Characters in a Golang String?
26 Aug, 2019 In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you can count some specific Unicode code points or the number of non-overlapping instances of costr (Repeated Characters) in the string with the help of Count() function. This function returns a value which represents the total number of the given string or Unicode code points present in the string. It is defined under the strings package so, you have to import strings package in your program for accessing Count function. Syntax: func Count(str, costr string) int Here, str is the original string and costr is a string which we want to count. If the value of costr is empty, then this function returns 1 + the number of Unicode code points in str. Example: // Go program to illustrate how to// count the elements of the stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome to the online portal of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Counting the elements of the strings // Using Count() function res1 := strings.Count(str1, "o") res2 := strings.Count(str2, "do") // Here, it also counts white spaces res3 := strings.Count(str3, "") res4 := strings.Count("GeeksforGeeks, geeks", "as") // Displaying the result fmt.Println("\nResult 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) } Output: String 1: Welcome to the online portal of GeeksforGeeks String 2: My dog name is Dollar String 3: I like to play Ludo Result 1: 6 Result 2: 1 Result 3: 20 Result 4: 0 Golang Golang-String Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang How to Parse JSON in Golang? How to Trim a String in Golang? Different Ways to Find the Type of Variable in Golang How to convert a string in lower case in Golang? How to compare times in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 690, "s": 28, "text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go string, you can count some specific Unicode code points or the number of non-overlapping instances of costr (Repeated Characters) in the string with the help of Count() function. This function returns a value which represents the total number of the given string or Unicode code points present in the string. It is defined under the strings package so, you have to import strings package in your program for accessing Count function." }, { "code": null, "e": 698, "s": 690, "text": "Syntax:" }, { "code": null, "e": 732, "s": 698, "text": "func Count(str, costr string) int" }, { "code": null, "e": 916, "s": 732, "text": "Here, str is the original string and costr is a string which we want to count. If the value of costr is empty, then this function returns 1 + the number of Unicode code points in str." }, { "code": null, "e": 925, "s": 916, "text": "Example:" }, { "code": "// Go program to illustrate how to// count the elements of the stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome to the online portal of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Counting the elements of the strings // Using Count() function res1 := strings.Count(str1, \"o\") res2 := strings.Count(str2, \"do\") // Here, it also counts white spaces res3 := strings.Count(str3, \"\") res4 := strings.Count(\"GeeksforGeeks, geeks\", \"as\") // Displaying the result fmt.Println(\"\\nResult 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }", "e": 1830, "s": 925, "text": null }, { "code": null, "e": 1838, "s": 1830, "text": "Output:" }, { "code": null, "e": 2014, "s": 1838, "text": "String 1: Welcome to the online portal of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nResult 1: 6\nResult 2: 1\nResult 3: 20\nResult 4: 0\n" }, { "code": null, "e": 2021, "s": 2014, "text": "Golang" }, { "code": null, "e": 2035, "s": 2021, "text": "Golang-String" }, { "code": null, "e": 2047, "s": 2035, "text": "Go Language" }, { "code": null, "e": 2145, "s": 2047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2158, "s": 2145, "text": "Arrays in Go" }, { "code": null, "e": 2170, "s": 2158, "text": "Golang Maps" }, { "code": null, "e": 2203, "s": 2170, "text": "How to Split a String in Golang?" }, { "code": null, "e": 2224, "s": 2203, "text": "Interfaces in Golang" }, { "code": null, "e": 2241, "s": 2224, "text": "Slices in Golang" }, { "code": null, "e": 2270, "s": 2241, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2302, "s": 2270, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 2356, "s": 2302, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 2405, "s": 2356, "text": "How to convert a string in lower case in Golang?" } ]
Program to print a string in vertical zigzag manner
06 Jul, 2021 Given a string, S of size N, and a number of rows R, the task is to print the given string in a vertical zigzag fashion with respect to the given number of rows as shown in the examples. Examples: Input: S = “123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”, R = 9Output: Input: S = “AttentionReaders!Don’tStopLearning!HappyLearning!”, R = 12Output: Approach: In order to print the characters line by line, the idea is to find the interval between the major columns and step value for in-between columns for printing the spaces until the last character of the string is reached. Follow the steps below to solve this problem: Initialize a variable interval as 2*R-2 to store the gap between the major columns. Iterate in the range [0, R-1] using the variable iInitialize a variable step as interval-2*i to store step values for each row.Iterate in the range [i, N-1] using the variable j, incrementing j by interval in each iteration,Print the character, S[j].If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces.Else print (interval-R) number of spaces.Print newline after each iteration of the outer loop. Initialize a variable step as interval-2*i to store step values for each row. Iterate in the range [i, N-1] using the variable j, incrementing j by interval in each iteration,Print the character, S[j].If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces.Else print (interval-R) number of spaces. Print the character, S[j]. If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces. Else print (interval-R) number of spaces. Print newline after each iteration of the outer loop. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print any string// in zigzag fashionvoid zigzag(string s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for (int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for (int j = i; j < s.length(); j = j + interval) { // Print the character cout << s[j]; if (step > 0 && step < interval && step + j < s.length()) { // Print the spaces before character // s[j+step] for (int k = 0; k < (interval - rows - i); k++) cout << " "; // Print the character cout << s[j + step]; // Print the spaces after character // after s[j+step] for (int k = 0; k < i - 1; k++) cout << " "; } else { // Print the spaces for first and last rows for (int k = 0; k < (interval - rows); k++) cout << " "; } } cout << endl; }} // Driver Codeint main(){ // Given Input string s = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh" "ijklmnopqrstuvwxyz"; int rows = 9; // Function Call zigzag(s, rows);} // Java program for the above approach public class GFG{ // Function to print any string// in zigzag fashionstatic void zigzag(String s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for(int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for(int j = i; j < s.length(); j = j + interval) { // Print the character System.out.print(s.charAt(j)); if (step > 0 && step < interval && step + j < s.length()) { // Print the spaces before character // s[j+step] for(int k = 0; k < (interval - rows - i); k++) System.out.print(" "); // Print the character System.out.print(s.charAt(j + step)); // Print the spaces after character // after s[j+step] for(int k = 0; k < i - 1; k++) System.out.print(" "); } else { // Print the spaces for first and last rows for(int k = 0; k < (interval - rows); k++) System.out.print(" "); } } System.out.println(); }} // Driver Codepublic static void main(String args[]){ // Given Input String s = "123456789ABCDEFGHIJKLM" + "NOPQRSTUVWXYZabcdefghi" + "jklmnopqrstuvwxyz"; int rows = 9; // Function Call zigzag(s, rows);}} // This code is contributed by SoumikMondal # Python3 program for the above approach # Function to print any string# in zigzag fashiondef zigzag(s, rows): # Store the gap between the major columns interval = 2 * rows - 2 # Traverse through rows for i in range(rows): # Store the step value for each row step = interval - 2 * i # Iterate in the range [1, N-1] for j in range(i, len(s), interval): # Print the character print(s[j], end = "") if (step > 0 and step < interval and step + j < len(s)): # Print the spaces before character # s[j+step] for k in range((interval - rows - i)): print(end = " ") # Print the character print(s[j + step], end = "") # Print the spaces after character # after s[j+step] for k in range(i - 1): print(end = " ") else: # Print the spaces for first and # last rows for k in range(interval - rows): print(end = " ") print() # Driver Codeif __name__ == '__main__': # Given Input s = "123456789ABCDEFGHIJKL"\ "MNOPQRSTUVWXYZabcdefghi"\ "jklmnopqrstuvwxyz" rows = 9 # Function Call zigzag(s, rows) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print any string// in zigzag fashionstatic void zigzag(string s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for(int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for(int j = i; j < s.Length; j = j + interval) { // Print the character Console.Write(s[j]); if (step > 0 && step < interval && step + j < s.Length) { // Print the spaces before character // s[j+step] for(int k = 0; k < (interval - rows - i); k++) Console.Write(" "); // Print the character Console.Write(s[j + step]); // Print the spaces after character // after s[j+step] for(int k = 0; k < i - 1; k++) Console.Write(" "); } else { // Print the spaces for first and last rows for(int k = 0; k < (interval - rows); k++) Console.Write(" "); } } Console.WriteLine(); }} // Driver Codepublic static void Main(){ // Given Input string s = "123456789ABCDEFGHIJKLM" + "NOPQRSTUVWXYZabcdefghi" + "jklmnopqrstuvwxyz"; int rows = 9; // Function Call zigzag(s, rows);}} // This code is contributed by SURENDRA_GANGWAR <script> // JavaScript program for the above approach // Function to print any string// in zigzag fashionfunction zigzag(s,rows){ // Store the gap between the major columns let interval = 2 * rows - 2; // Traverse through rows for(let i = 0; i < rows; i++) { // Store the step value for each row let step = interval - 2 * i; // Iterate in the range [1, N-1] for(let j = i; j < s.length; j = j + interval) { // Print the character document.write(s[j]); if (step > 0 && step < interval && step + j < s.length) { // Print the spaces before character // s[j+step] for(let k = 0; k < (interval - rows - i); k++) document.write(" "); // Print the character document.write(s[j + step]); // Print the spaces after character // after s[j+step] for(let k = 0; k < i - 1; k++) document.write(" "); } else { // Print the spaces for first and last rows for(let k = 0; k < (interval - rows); k++) document.write(" "); } } document.write("<br>"); }} // Driver Code// Given Inputlet s = "123456789ABCDEFGHIJKLM" + "NOPQRSTUVWXYZabcdefghi" + "jklmnopqrstuvwxyz";let rows = 9; // Function Callzigzag(s, rows); // This code is contributed by patel2127 </script> 1 H X n 2 GI WY mo 3 F J V Z l p 4 E K U a k q 5 D L T b j r z 6 C M S c i s y 7 B N R d h t x 8A OQ eg uw 9 P f v Time Complexity: O(R2*N)Auxiliary Space: O(1) mohit kumar 29 SURENDRA_GANGWAR SoumikMondal patel2127 pattern-printing Strings Strings pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Check if an URL is valid or not using Regular Expression Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2021" }, { "code": null, "e": 239, "s": 52, "text": "Given a string, S of size N, and a number of rows R, the task is to print the given string in a vertical zigzag fashion with respect to the given number of rows as shown in the examples." }, { "code": null, "e": 249, "s": 239, "text": "Examples:" }, { "code": null, "e": 338, "s": 249, "text": "Input: S = “123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”, R = 9Output:" }, { "code": null, "e": 416, "s": 338, "text": "Input: S = “AttentionReaders!Don’tStopLearning!HappyLearning!”, R = 12Output:" }, { "code": null, "e": 691, "s": 416, "text": "Approach: In order to print the characters line by line, the idea is to find the interval between the major columns and step value for in-between columns for printing the spaces until the last character of the string is reached. Follow the steps below to solve this problem:" }, { "code": null, "e": 775, "s": 691, "text": "Initialize a variable interval as 2*R-2 to store the gap between the major columns." }, { "code": null, "e": 1285, "s": 775, "text": "Iterate in the range [0, R-1] using the variable iInitialize a variable step as interval-2*i to store step values for each row.Iterate in the range [i, N-1] using the variable j, incrementing j by interval in each iteration,Print the character, S[j].If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces.Else print (interval-R) number of spaces.Print newline after each iteration of the outer loop." }, { "code": null, "e": 1363, "s": 1285, "text": "Initialize a variable step as interval-2*i to store step values for each row." }, { "code": null, "e": 1693, "s": 1363, "text": "Iterate in the range [i, N-1] using the variable j, incrementing j by interval in each iteration,Print the character, S[j].If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces.Else print (interval-R) number of spaces." }, { "code": null, "e": 1720, "s": 1693, "text": "Print the character, S[j]." }, { "code": null, "e": 1886, "s": 1720, "text": "If the value of step lies in the range [1, interval-1] and step+j<N, then print (interval-R-i) number of spaces, then print s[j+step] and finally print (i-1) spaces." }, { "code": null, "e": 1928, "s": 1886, "text": "Else print (interval-R) number of spaces." }, { "code": null, "e": 1982, "s": 1928, "text": "Print newline after each iteration of the outer loop." }, { "code": null, "e": 2033, "s": 1982, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2037, "s": 2033, "text": "C++" }, { "code": null, "e": 2042, "s": 2037, "text": "Java" }, { "code": null, "e": 2050, "s": 2042, "text": "Python3" }, { "code": null, "e": 2053, "s": 2050, "text": "C#" }, { "code": null, "e": 2064, "s": 2053, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print any string// in zigzag fashionvoid zigzag(string s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for (int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for (int j = i; j < s.length(); j = j + interval) { // Print the character cout << s[j]; if (step > 0 && step < interval && step + j < s.length()) { // Print the spaces before character // s[j+step] for (int k = 0; k < (interval - rows - i); k++) cout << \" \"; // Print the character cout << s[j + step]; // Print the spaces after character // after s[j+step] for (int k = 0; k < i - 1; k++) cout << \" \"; } else { // Print the spaces for first and last rows for (int k = 0; k < (interval - rows); k++) cout << \" \"; } } cout << endl; }} // Driver Codeint main(){ // Given Input string s = \"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh\" \"ijklmnopqrstuvwxyz\"; int rows = 9; // Function Call zigzag(s, rows);}", "e": 3566, "s": 2064, "text": null }, { "code": "// Java program for the above approach public class GFG{ // Function to print any string// in zigzag fashionstatic void zigzag(String s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for(int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for(int j = i; j < s.length(); j = j + interval) { // Print the character System.out.print(s.charAt(j)); if (step > 0 && step < interval && step + j < s.length()) { // Print the spaces before character // s[j+step] for(int k = 0; k < (interval - rows - i); k++) System.out.print(\" \"); // Print the character System.out.print(s.charAt(j + step)); // Print the spaces after character // after s[j+step] for(int k = 0; k < i - 1; k++) System.out.print(\" \"); } else { // Print the spaces for first and last rows for(int k = 0; k < (interval - rows); k++) System.out.print(\" \"); } } System.out.println(); }} // Driver Codepublic static void main(String args[]){ // Given Input String s = \"123456789ABCDEFGHIJKLM\" + \"NOPQRSTUVWXYZabcdefghi\" + \"jklmnopqrstuvwxyz\"; int rows = 9; // Function Call zigzag(s, rows);}} // This code is contributed by SoumikMondal", "e": 5285, "s": 3566, "text": null }, { "code": "# Python3 program for the above approach # Function to print any string# in zigzag fashiondef zigzag(s, rows): # Store the gap between the major columns interval = 2 * rows - 2 # Traverse through rows for i in range(rows): # Store the step value for each row step = interval - 2 * i # Iterate in the range [1, N-1] for j in range(i, len(s), interval): # Print the character print(s[j], end = \"\") if (step > 0 and step < interval and step + j < len(s)): # Print the spaces before character # s[j+step] for k in range((interval - rows - i)): print(end = \" \") # Print the character print(s[j + step], end = \"\") # Print the spaces after character # after s[j+step] for k in range(i - 1): print(end = \" \") else: # Print the spaces for first and # last rows for k in range(interval - rows): print(end = \" \") print() # Driver Codeif __name__ == '__main__': # Given Input s = \"123456789ABCDEFGHIJKL\"\\ \"MNOPQRSTUVWXYZabcdefghi\"\\ \"jklmnopqrstuvwxyz\" rows = 9 # Function Call zigzag(s, rows) # This code is contributed by mohit kumar 29", "e": 6750, "s": 5285, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print any string// in zigzag fashionstatic void zigzag(string s, int rows){ // Store the gap between the major columns int interval = 2 * rows - 2; // Traverse through rows for(int i = 0; i < rows; i++) { // Store the step value for each row int step = interval - 2 * i; // Iterate in the range [1, N-1] for(int j = i; j < s.Length; j = j + interval) { // Print the character Console.Write(s[j]); if (step > 0 && step < interval && step + j < s.Length) { // Print the spaces before character // s[j+step] for(int k = 0; k < (interval - rows - i); k++) Console.Write(\" \"); // Print the character Console.Write(s[j + step]); // Print the spaces after character // after s[j+step] for(int k = 0; k < i - 1; k++) Console.Write(\" \"); } else { // Print the spaces for first and last rows for(int k = 0; k < (interval - rows); k++) Console.Write(\" \"); } } Console.WriteLine(); }} // Driver Codepublic static void Main(){ // Given Input string s = \"123456789ABCDEFGHIJKLM\" + \"NOPQRSTUVWXYZabcdefghi\" + \"jklmnopqrstuvwxyz\"; int rows = 9; // Function Call zigzag(s, rows);}} // This code is contributed by SURENDRA_GANGWAR", "e": 8463, "s": 6750, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to print any string// in zigzag fashionfunction zigzag(s,rows){ // Store the gap between the major columns let interval = 2 * rows - 2; // Traverse through rows for(let i = 0; i < rows; i++) { // Store the step value for each row let step = interval - 2 * i; // Iterate in the range [1, N-1] for(let j = i; j < s.length; j = j + interval) { // Print the character document.write(s[j]); if (step > 0 && step < interval && step + j < s.length) { // Print the spaces before character // s[j+step] for(let k = 0; k < (interval - rows - i); k++) document.write(\" \"); // Print the character document.write(s[j + step]); // Print the spaces after character // after s[j+step] for(let k = 0; k < i - 1; k++) document.write(\" \"); } else { // Print the spaces for first and last rows for(let k = 0; k < (interval - rows); k++) document.write(\" \"); } } document.write(\"<br>\"); }} // Driver Code// Given Inputlet s = \"123456789ABCDEFGHIJKLM\" + \"NOPQRSTUVWXYZabcdefghi\" + \"jklmnopqrstuvwxyz\";let rows = 9; // Function Callzigzag(s, rows); // This code is contributed by patel2127 </script>", "e": 10061, "s": 8463, "text": null }, { "code": null, "e": 10358, "s": 10061, "text": "1 H X n \n2 GI WY mo \n3 F J V Z l p \n4 E K U a k q \n5 D L T b j r z \n6 C M S c i s y \n7 B N R d h t x \n8A OQ eg uw \n9 P f v " }, { "code": null, "e": 10404, "s": 10358, "text": "Time Complexity: O(R2*N)Auxiliary Space: O(1)" }, { "code": null, "e": 10421, "s": 10406, "text": "mohit kumar 29" }, { "code": null, "e": 10438, "s": 10421, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 10451, "s": 10438, "text": "SoumikMondal" }, { "code": null, "e": 10461, "s": 10451, "text": "patel2127" }, { "code": null, "e": 10478, "s": 10461, "text": "pattern-printing" }, { "code": null, "e": 10486, "s": 10478, "text": "Strings" }, { "code": null, "e": 10494, "s": 10486, "text": "Strings" }, { "code": null, "e": 10511, "s": 10494, "text": "pattern-printing" }, { "code": null, "e": 10609, "s": 10511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10654, "s": 10609, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 10718, "s": 10654, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 10763, "s": 10718, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 10798, "s": 10763, "text": "Print all subsequences of a string" }, { "code": null, "e": 10863, "s": 10798, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 10892, "s": 10863, "text": "String class in Java | Set 1" }, { "code": null, "e": 10953, "s": 10892, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 11005, "s": 10953, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 11062, "s": 11005, "text": "Check if an URL is valid or not using Regular Expression" } ]
try-except vs If in Python
13 Aug, 2021 Python is a widely used general-purpose, high level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.Most of the people don’t know that Try-Except block can replace if-else (conditional Statements). Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements. Here is a very famous example :Using If: if key in mydict: mydict[key] += 1 else: mydict[key] = 1 Using try/except: try: mydict[key] += 1 except KeyError: mydict[key] = 1 It seems awesome right! But here comes the thing, Which code block works faster? It can be measured using the timeit module in python. It can be seen whether Try block should be used instead of If. Example: Time comparison for division of 2 numbers using try-except and if-else.Below is the implementation. Python3 import timeit code_snippets =["""\try: result = 1000 / valueexcept ZeroDivisionError: pass""","""\if value: result = 1000 / value""",] for value in (1, 0): for code in code_snippets: t = timeit.Timer(stmt = code, setup ='value ={}'.format(value)) print("----------------------") print("value = {}\n{}".format(value, code)) print("%.2f usec / pass\n" % (1000000 * t.timeit(number = 100000)/100000)) Output: ---------------------- value = 1 try: result = 1000 / value except ZeroDivisionError: pass 0.04 usec / pass ---------------------- value = 1 if value: result = 1000 / value 0.06 usec / pass ---------------------- value = 0 try: result = 1000 / value except ZeroDivisionError: pass 0.37 usec / pass ---------------------- value = 0 if value: result = 1000 / value 0.01 usec / pass Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code. That means the factor that decides the fastness of the code is the type of problem that is being handled.We often hear that python always encourages EAFP(“It’s easier to ask for forgiveness than permission”) style over LBYL ( “Look before you leap ” ) style used in most of the languages like C. Python docs states that – Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C. From our evaluation, we come to the following conclusion. Let’s consider our above example, if we expect that 99% of the cases the values of ‘value’ will not be equal to 0, we can use try/except approach. It will be faster if the exception really is exceptional. If the possibility of value becomes 0 is more than 50 %, then using ‘if’ is probably better. Akanksha_Rai akshaysingh98088 Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Aug, 2021" }, { "code": null, "e": 586, "s": 52, "text": "Python is a widely used general-purpose, high level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.Most of the people don’t know that Try-Except block can replace if-else (conditional Statements). Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements. " }, { "code": null, "e": 628, "s": 586, "text": "Here is a very famous example :Using If: " }, { "code": null, "e": 693, "s": 628, "text": "if key in mydict:\n mydict[key] += 1\nelse:\n mydict[key] = 1" }, { "code": null, "e": 711, "s": 693, "text": "Using try/except:" }, { "code": null, "e": 774, "s": 711, "text": "try:\n mydict[key] += 1\nexcept KeyError:\n mydict[key] = 1" }, { "code": null, "e": 1081, "s": 774, "text": "It seems awesome right! But here comes the thing, Which code block works faster? It can be measured using the timeit module in python. It can be seen whether Try block should be used instead of If. Example: Time comparison for division of 2 numbers using try-except and if-else.Below is the implementation." }, { "code": null, "e": 1089, "s": 1081, "text": "Python3" }, { "code": "import timeit code_snippets =[\"\"\"\\try: result = 1000 / valueexcept ZeroDivisionError: pass\"\"\",\"\"\"\\if value: result = 1000 / value\"\"\",] for value in (1, 0): for code in code_snippets: t = timeit.Timer(stmt = code, setup ='value ={}'.format(value)) print(\"----------------------\") print(\"value = {}\\n{}\".format(value, code)) print(\"%.2f usec / pass\\n\" % (1000000 * t.timeit(number = 100000)/100000))", "e": 1527, "s": 1089, "text": null }, { "code": null, "e": 1536, "s": 1527, "text": "Output: " }, { "code": null, "e": 1943, "s": 1536, "text": "----------------------\nvalue = 1\ntry:\n result = 1000 / value\nexcept ZeroDivisionError:\n pass\n0.04 usec / pass\n\n----------------------\nvalue = 1\nif value:\n result = 1000 / value\n0.06 usec / pass\n\n----------------------\nvalue = 0\ntry:\n result = 1000 / value\nexcept ZeroDivisionError:\n pass\n0.37 usec / pass\n\n----------------------\nvalue = 0\nif value:\n result = 1000 / value\n0.01 usec / pass" }, { "code": null, "e": 2520, "s": 1943, "text": "Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code. That means the factor that decides the fastness of the code is the type of problem that is being handled.We often hear that python always encourages EAFP(“It’s easier to ask for forgiveness than permission”) style over LBYL ( “Look before you leap ” ) style used in most of the languages like C. Python docs states that – " }, { "code": null, "e": 2884, "s": 2520, "text": "Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C." }, { "code": null, "e": 3240, "s": 2884, "text": "From our evaluation, we come to the following conclusion. Let’s consider our above example, if we expect that 99% of the cases the values of ‘value’ will not be equal to 0, we can use try/except approach. It will be faster if the exception really is exceptional. If the possibility of value becomes 0 is more than 50 %, then using ‘if’ is probably better." }, { "code": null, "e": 3253, "s": 3240, "text": "Akanksha_Rai" }, { "code": null, "e": 3270, "s": 3253, "text": "akshaysingh98088" }, { "code": null, "e": 3288, "s": 3270, "text": "Python-exceptions" }, { "code": null, "e": 3295, "s": 3288, "text": "Python" } ]
Find winner of an election where votes are represented as candidate names
25 May, 2022 Given an array of names of candidates in an election. A candidate’s name in the array represents a vote cast on the candidate. Print the name of candidates who received the maximum vote. If there is a tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john"}; Output : John We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The candidates John and Johny get maximum votes. Since John is alphabetically smaller, we print it. A simple solution is to run two loops and count the occurrences of every word. The time complexity of this solution is O(n * n * MAX_WORD_LEN). An efficient solution is to use Hashing. We insert all votes in a hash map and keep track of counts of different names. Finally, we traverse the map and print the person with the maximum votes. C++ Java Python3 C# Javascript // C++++ program to find winner in an election.#include "bits/stdc++.h"using namespace std; /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ void findWinner(vector<string>& votes) { // Insert all votes in a hashmap unordered_map<string,int> mapObj ; for (auto& str : votes) { mapObj[str]++; } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; string winner; for (auto& entry : mapObj) { string key = entry.first; int val = entry.second; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>key) winner = key; } cout << winner << endl; } // Driver code int main() { vector<string> votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); return 0; } // Java program to find winner in an election.import java.util.*; public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String votes[]) { // Insert all votes in a hashmap Map<String,Integer> map = new HashMap<String, Integer>(); for (String str : votes) { if (map.keySet().contains(str)) map.put(str, map.get(str) + 1); else map.put(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = ""; for (Map.Entry<String,Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.compareTo(key) > 0) winner = key; } System.out.println(winner); } // Driver code public static void main(String[] args) { String[] votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); }} # Python3 program to find winner in an election.from collections import defaultdict ''' We have four Candidates with name as 'John','Johnny', 'jamie', 'jackie'.The votes in String array are as per thevotes casted. Print the name of candidatesreceived Max vote. '''def findWinner(votes): # Insert all votes in a hashmap mapObj = defaultdict(int) for st in votes: mapObj[st] += 1 # Traverse through map to find the # candidate with maximum votes. maxValueInMap = 0 winner = "" for entry in mapObj: key = entry val = mapObj[entry] if (val > maxValueInMap): maxValueInMap = val winner = key # If there is a tie, pick lexicographically # smaller. else if (val == maxValueInMap and winner > key): winner = key print(winner) # Driver codeif __name__ == "__main__": votes = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" ] findWinner(votes) # This code is contributed by ukasp // C# program to find winner in an election.using System;using System.Collections.Generic; public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String []votes) { // Insert all votes in a hashmap Dictionary<String,int> map = new Dictionary<String, int>(); foreach (String str in votes) { if (map.ContainsKey(str)) map[str] = map[str] + 1; else map.Add(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = ""; foreach(KeyValuePair<String, int> entry in map) { String key = entry.Key; int val = entry.Value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.CompareTo(key) > 0) winner = key; } Console.WriteLine(winner); } // Driver code public static void Main(String[] args) { String[] votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); }} // This code is contributed by PrinciRaj1992 <script>// Javascript program to find winner in an election. /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ function findWinner(votes) { let map = new Map(); for(let i=0;i<votes.length;i++) { if(map.has(votes[i])) { map.set(votes[i], map.get(votes[i]) + 1); } else map.set(votes[i], 1); } // Traverse through map to find the candidate // with maximum votes. let maxValueInMap = 0; let winner = ""; for (let [key, value] of map.entries()) { let Key = key; let val = value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>Key) winner = Key; } document.write(winner); } // Driver code let votes=["john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john"]; findWinner(votes); // This code is contributed by rag2127</script> Output: John Time Complexity: O(n)), where n is the total number of votes. Auxiliary Space: O(n), since unordered_map data structure is used. Another efficient solution is to use Trie. Please refer most frequent word in an array of strings.This article is contributed by Ishfaq Ramzan Nagoo. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Ankit Verma 10 princiraj1992 ukasp rag2127 aadityamp01 surinderdawra388 shivamanandrj9 Adobe Java-HashMap Microsoft Hash Strings Microsoft Adobe Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 298, "s": 52, "text": "Given an array of names of candidates in an election. A candidate’s name in the array represents a vote cast on the candidate. Print the name of candidates who received the maximum vote. If there is a tie, print a lexicographically smaller name." }, { "code": null, "e": 309, "s": 298, "text": "Examples: " }, { "code": null, "e": 721, "s": 309, "text": "Input : votes[] = {\"john\", \"johnny\", \"jackie\", \n \"johnny\", \"john\", \"jackie\", \n \"jamie\", \"jamie\", \"john\",\n \"johnny\", \"jamie\", \"johnny\", \n \"john\"};\nOutput : John\nWe have four Candidates with name as 'John', \n'Johnny', 'jamie', 'jackie'. The candidates\nJohn and Johny get maximum votes. Since John\nis alphabetically smaller, we print it." }, { "code": null, "e": 865, "s": 721, "text": "A simple solution is to run two loops and count the occurrences of every word. The time complexity of this solution is O(n * n * MAX_WORD_LEN)." }, { "code": null, "e": 1059, "s": 865, "text": "An efficient solution is to use Hashing. We insert all votes in a hash map and keep track of counts of different names. Finally, we traverse the map and print the person with the maximum votes." }, { "code": null, "e": 1063, "s": 1059, "text": "C++" }, { "code": null, "e": 1068, "s": 1063, "text": "Java" }, { "code": null, "e": 1076, "s": 1068, "text": "Python3" }, { "code": null, "e": 1079, "s": 1076, "text": "C#" }, { "code": null, "e": 1090, "s": 1079, "text": "Javascript" }, { "code": "// C++++ program to find winner in an election.#include \"bits/stdc++.h\"using namespace std; /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ void findWinner(vector<string>& votes) { // Insert all votes in a hashmap unordered_map<string,int> mapObj ; for (auto& str : votes) { mapObj[str]++; } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; string winner; for (auto& entry : mapObj) { string key = entry.first; int val = entry.second; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>key) winner = key; } cout << winner << endl; } // Driver code int main() { vector<string> votes = { \"john\", \"johnny\", \"jackie\", \"johnny\", \"john\", \"jackie\", \"jamie\", \"jamie\", \"john\", \"johnny\", \"jamie\", \"johnny\", \"john\" }; findWinner(votes); return 0; } ", "e": 2550, "s": 1090, "text": null }, { "code": "// Java program to find winner in an election.import java.util.*; public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String votes[]) { // Insert all votes in a hashmap Map<String,Integer> map = new HashMap<String, Integer>(); for (String str : votes) { if (map.keySet().contains(str)) map.put(str, map.get(str) + 1); else map.put(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = \"\"; for (Map.Entry<String,Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.compareTo(key) > 0) winner = key; } System.out.println(winner); } // Driver code public static void main(String[] args) { String[] votes = { \"john\", \"johnny\", \"jackie\", \"johnny\", \"john\", \"jackie\", \"jamie\", \"jamie\", \"john\", \"johnny\", \"jamie\", \"johnny\", \"john\" }; findWinner(votes); }}", "e": 4234, "s": 2550, "text": null }, { "code": "# Python3 program to find winner in an election.from collections import defaultdict ''' We have four Candidates with name as 'John','Johnny', 'jamie', 'jackie'.The votes in String array are as per thevotes casted. Print the name of candidatesreceived Max vote. '''def findWinner(votes): # Insert all votes in a hashmap mapObj = defaultdict(int) for st in votes: mapObj[st] += 1 # Traverse through map to find the # candidate with maximum votes. maxValueInMap = 0 winner = \"\" for entry in mapObj: key = entry val = mapObj[entry] if (val > maxValueInMap): maxValueInMap = val winner = key # If there is a tie, pick lexicographically # smaller. else if (val == maxValueInMap and winner > key): winner = key print(winner) # Driver codeif __name__ == \"__main__\": votes = [ \"john\", \"johnny\", \"jackie\", \"johnny\", \"john\", \"jackie\", \"jamie\", \"jamie\", \"john\", \"johnny\", \"jamie\", \"johnny\", \"john\" ] findWinner(votes) # This code is contributed by ukasp", "e": 5381, "s": 4234, "text": null }, { "code": "// C# program to find winner in an election.using System;using System.Collections.Generic; public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String []votes) { // Insert all votes in a hashmap Dictionary<String,int> map = new Dictionary<String, int>(); foreach (String str in votes) { if (map.ContainsKey(str)) map[str] = map[str] + 1; else map.Add(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = \"\"; foreach(KeyValuePair<String, int> entry in map) { String key = entry.Key; int val = entry.Value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.CompareTo(key) > 0) winner = key; } Console.WriteLine(winner); } // Driver code public static void Main(String[] args) { String[] votes = { \"john\", \"johnny\", \"jackie\", \"johnny\", \"john\", \"jackie\", \"jamie\", \"jamie\", \"john\", \"johnny\", \"jamie\", \"johnny\", \"john\" }; findWinner(votes); }} // This code is contributed by PrinciRaj1992", "e": 7113, "s": 5381, "text": null }, { "code": "<script>// Javascript program to find winner in an election. /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ function findWinner(votes) { let map = new Map(); for(let i=0;i<votes.length;i++) { if(map.has(votes[i])) { map.set(votes[i], map.get(votes[i]) + 1); } else map.set(votes[i], 1); } // Traverse through map to find the candidate // with maximum votes. let maxValueInMap = 0; let winner = \"\"; for (let [key, value] of map.entries()) { let Key = key; let val = value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>Key) winner = Key; } document.write(winner); } // Driver code let votes=[\"john\", \"johnny\", \"jackie\", \"johnny\", \"john\", \"jackie\", \"jamie\", \"jamie\", \"john\", \"johnny\", \"jamie\", \"johnny\", \"john\"]; findWinner(votes); // This code is contributed by rag2127</script>", "e": 8647, "s": 7113, "text": null }, { "code": null, "e": 8656, "s": 8647, "text": "Output: " }, { "code": null, "e": 8661, "s": 8656, "text": "John" }, { "code": null, "e": 8723, "s": 8661, "text": "Time Complexity: O(n)), where n is the total number of votes." }, { "code": null, "e": 8790, "s": 8723, "text": "Auxiliary Space: O(n), since unordered_map data structure is used." }, { "code": null, "e": 9316, "s": 8790, "text": "Another efficient solution is to use Trie. Please refer most frequent word in an array of strings.This article is contributed by Ishfaq Ramzan Nagoo. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9331, "s": 9316, "text": "Ankit Verma 10" }, { "code": null, "e": 9345, "s": 9331, "text": "princiraj1992" }, { "code": null, "e": 9351, "s": 9345, "text": "ukasp" }, { "code": null, "e": 9359, "s": 9351, "text": "rag2127" }, { "code": null, "e": 9371, "s": 9359, "text": "aadityamp01" }, { "code": null, "e": 9388, "s": 9371, "text": "surinderdawra388" }, { "code": null, "e": 9403, "s": 9388, "text": "shivamanandrj9" }, { "code": null, "e": 9409, "s": 9403, "text": "Adobe" }, { "code": null, "e": 9422, "s": 9409, "text": "Java-HashMap" }, { "code": null, "e": 9432, "s": 9422, "text": "Microsoft" }, { "code": null, "e": 9437, "s": 9432, "text": "Hash" }, { "code": null, "e": 9445, "s": 9437, "text": "Strings" }, { "code": null, "e": 9455, "s": 9445, "text": "Microsoft" }, { "code": null, "e": 9461, "s": 9455, "text": "Adobe" }, { "code": null, "e": 9466, "s": 9461, "text": "Hash" }, { "code": null, "e": 9474, "s": 9466, "text": "Strings" } ]
Repeated subtraction among two numbers
02 Mar, 2021 Given a pair of positive numbers x and y. We repeatedly subtract the smaller of the two integers from greater one until one of the integers becomes 0. The task is to count number of steps to before we stop (one of the numbers become 0). Examples : Input : x = 5, y = 13 Output : 6 Explanation : There are total 6 steps before we reach 0: (5,13) --> (5,8) --> (5,3) --> (2,3) --> (2,1) --> (1,1) --> (1,0). Input : x = 3, y = 5 Output : 4 Explanation : There are 4 steps: (5,3) --> (2,3) --> (2,1) --> (1,1) --> (1,0) Input : x = 100, y = 19 Output : 13 A simple solution is to actually follow the process and count the number of steps. A better solution is to use below steps. Let y be the smaller of two numbers 1) if y divides x then return (x/y) 2) else return ( (x/y) + solve(y, x%y) )Illustration : If we start with (x, y) and y divides x then the answer will be (x/y) since we can subtract y form x exactly (x/y) times.For the other case, we take an example to see how it works: (100, 19)We can subtract 19 from 100 exactly [100/19] = 5 times to get (19, 5).We can subtract 5 from 19 exactly [19/5] = 3 times to get (5, 4).We can subtract 4 from 5 exactly [5/4] = 1 times to get (4, 1).We can subtract 1 from 4 exactly [4/1] = 4 times to get (1, 0)hence a total of 5 + 3 + 1 + 4 = 13 steps.Below is implementation based on above idea. C++ Java Python3 C# PHP Javascript // C++ program to count of steps until one// of the two numbers become 0.#include<bits/stdc++.h>using namespace std; // Returns count of steps before one// of the numbers become 0 after repeated// subtractions.int countSteps(int x, int y){ // If y divides x, then simply return // x/y. if (x%y == 0) return x/y; // Else recur. Note that this function // works even if x is smaller than y because // in that case first recursive call exchanges // roles of x and y. return x/y + countSteps(y, x%y);} // Driver codeint main(){ int x = 100, y = 19; cout << countSteps(x, y); return 0;} // Java program to count of// steps until one of the// two numbers become 0.import java.io.*; class GFG{ // Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.static int countSteps(int x, int y){ // If y divides x, then // simply return x/y. if (x % y == 0) return x / y; // Else recur. Note that this // function works even if x is // smaller than y because // in that case first recursive // call exchanges roles of x and y. return x / y + countSteps(y, x % y);} // Driver codepublic static void main (String[] args){ int x = 100, y = 19; System.out.println(countSteps(x, y)); }} // This code is contributed by aj_36 # Python3 program to count of steps until# one of the two numbers become 0.import math # Returns count of steps before one of# the numbers become 0 after repeated# subtractions.def countSteps(x, y): # If y divides x, then simply # return x/y. if (x % y == 0): return math.floor(x / y); # Else recur. Note that this function # works even if x is smaller than y # because in that case first recursive # call exchanges roles of x and y. return math.floor((x / y) + countSteps(y, x % y)); # Driver codex = 100;y = 19;print(countSteps(x, y)); # This code is contributed by mits // C# program to count of// steps until one of the// two numbers become 0.using System; class GFG{// Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.static int countSteps(int x, int y){ // If y divides x, then // simply return x/y. if (x % y == 0) return x / y; // Else recur. Note that this // function works even if x is // smaller than y because // in that case first recursive // call exchanges roles of x and y. return x / y + countSteps(y, x % y);} // Driver Codestatic public void Main (){int x = 100, y = 19;Console.WriteLine(countSteps(x, y));}} // This code is contributed by m_kit <?php// PHP program to count of// steps until one of the// two numbers become 0. // Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.function countSteps($x, $y){ // If y divides x, then // simply return x/y. if ($x % $y == 0) return floor(((int)$x / $y)); // Else recur. Note that this // function works even if x is // smaller than y because in that // case first recursive call // exchanges roles of x and y. return floor(((int)$x / $y) + countSteps($y, $x % $y));} // Driver code$x = 100;$y = 19;echo countSteps($x, $y); // This code is contributed by aj_36?> <script> // Javascript program to count of steps until one// of the two numbers become 0. // Returns count of steps before one// of the numbers become 0 after repeated// subtractions.function countSteps(x, y){ // If y divides x, then simply return // x/y. if (x%y == 0) return Math.floor(x/y); // Else recur. Note that this function // works even if x is smaller than y because // in that case first recursive call exchanges // roles of x and y. return Math.floor(x/y) + countSteps(y, x%y);} // Driver code let x = 100, y = 19; document.write(countSteps(x, y)); // This code is contributed by Mayank Tyagi </script> Output : 13 Time Complexity: O(log(n)) Auxiliary Space: O(1)This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar subhammahato348 mayanktyagi1709 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Mar, 2021" }, { "code": null, "e": 301, "s": 52, "text": "Given a pair of positive numbers x and y. We repeatedly subtract the smaller of the two integers from greater one until one of the integers becomes 0. The task is to count number of steps to before we stop (one of the numbers become 0). Examples : " }, { "code": null, "e": 610, "s": 301, "text": "Input : x = 5, y = 13\nOutput : 6\nExplanation : There are total 6 steps before \nwe reach 0:\n(5,13) --> (5,8) --> (5,3) --> (2,3) \n--> (2,1) --> (1,1) --> (1,0).\n\nInput : x = 3, y = 5\nOutput : 4\nExplanation : There are 4 steps:\n(5,3) --> (2,3) --> (2,1) --> (1,1) --> (1,0)\n\nInput : x = 100, y = 19\nOutput : 13" }, { "code": null, "e": 1398, "s": 610, "text": "A simple solution is to actually follow the process and count the number of steps. A better solution is to use below steps. Let y be the smaller of two numbers 1) if y divides x then return (x/y) 2) else return ( (x/y) + solve(y, x%y) )Illustration : If we start with (x, y) and y divides x then the answer will be (x/y) since we can subtract y form x exactly (x/y) times.For the other case, we take an example to see how it works: (100, 19)We can subtract 19 from 100 exactly [100/19] = 5 times to get (19, 5).We can subtract 5 from 19 exactly [19/5] = 3 times to get (5, 4).We can subtract 4 from 5 exactly [5/4] = 1 times to get (4, 1).We can subtract 1 from 4 exactly [4/1] = 4 times to get (1, 0)hence a total of 5 + 3 + 1 + 4 = 13 steps.Below is implementation based on above idea." }, { "code": null, "e": 1402, "s": 1398, "text": "C++" }, { "code": null, "e": 1407, "s": 1402, "text": "Java" }, { "code": null, "e": 1415, "s": 1407, "text": "Python3" }, { "code": null, "e": 1418, "s": 1415, "text": "C#" }, { "code": null, "e": 1422, "s": 1418, "text": "PHP" }, { "code": null, "e": 1433, "s": 1422, "text": "Javascript" }, { "code": "// C++ program to count of steps until one// of the two numbers become 0.#include<bits/stdc++.h>using namespace std; // Returns count of steps before one// of the numbers become 0 after repeated// subtractions.int countSteps(int x, int y){ // If y divides x, then simply return // x/y. if (x%y == 0) return x/y; // Else recur. Note that this function // works even if x is smaller than y because // in that case first recursive call exchanges // roles of x and y. return x/y + countSteps(y, x%y);} // Driver codeint main(){ int x = 100, y = 19; cout << countSteps(x, y); return 0;}", "e": 2053, "s": 1433, "text": null }, { "code": "// Java program to count of// steps until one of the// two numbers become 0.import java.io.*; class GFG{ // Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.static int countSteps(int x, int y){ // If y divides x, then // simply return x/y. if (x % y == 0) return x / y; // Else recur. Note that this // function works even if x is // smaller than y because // in that case first recursive // call exchanges roles of x and y. return x / y + countSteps(y, x % y);} // Driver codepublic static void main (String[] args){ int x = 100, y = 19; System.out.println(countSteps(x, y)); }} // This code is contributed by aj_36", "e": 2783, "s": 2053, "text": null }, { "code": "# Python3 program to count of steps until# one of the two numbers become 0.import math # Returns count of steps before one of# the numbers become 0 after repeated# subtractions.def countSteps(x, y): # If y divides x, then simply # return x/y. if (x % y == 0): return math.floor(x / y); # Else recur. Note that this function # works even if x is smaller than y # because in that case first recursive # call exchanges roles of x and y. return math.floor((x / y) + countSteps(y, x % y)); # Driver codex = 100;y = 19;print(countSteps(x, y)); # This code is contributed by mits", "e": 3403, "s": 2783, "text": null }, { "code": "// C# program to count of// steps until one of the// two numbers become 0.using System; class GFG{// Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.static int countSteps(int x, int y){ // If y divides x, then // simply return x/y. if (x % y == 0) return x / y; // Else recur. Note that this // function works even if x is // smaller than y because // in that case first recursive // call exchanges roles of x and y. return x / y + countSteps(y, x % y);} // Driver Codestatic public void Main (){int x = 100, y = 19;Console.WriteLine(countSteps(x, y));}} // This code is contributed by m_kit", "e": 4095, "s": 3403, "text": null }, { "code": "<?php// PHP program to count of// steps until one of the// two numbers become 0. // Returns count of steps// before one of the numbers// become 0 after repeated// subtractions.function countSteps($x, $y){ // If y divides x, then // simply return x/y. if ($x % $y == 0) return floor(((int)$x / $y)); // Else recur. Note that this // function works even if x is // smaller than y because in that // case first recursive call // exchanges roles of x and y. return floor(((int)$x / $y) + countSteps($y, $x % $y));} // Driver code$x = 100;$y = 19;echo countSteps($x, $y); // This code is contributed by aj_36?>", "e": 4754, "s": 4095, "text": null }, { "code": "<script> // Javascript program to count of steps until one// of the two numbers become 0. // Returns count of steps before one// of the numbers become 0 after repeated// subtractions.function countSteps(x, y){ // If y divides x, then simply return // x/y. if (x%y == 0) return Math.floor(x/y); // Else recur. Note that this function // works even if x is smaller than y because // in that case first recursive call exchanges // roles of x and y. return Math.floor(x/y) + countSteps(y, x%y);} // Driver code let x = 100, y = 19; document.write(countSteps(x, y)); // This code is contributed by Mayank Tyagi </script>", "e": 5410, "s": 4754, "text": null }, { "code": null, "e": 5420, "s": 5410, "text": "Output : " }, { "code": null, "e": 5423, "s": 5420, "text": "13" }, { "code": null, "e": 5450, "s": 5423, "text": "Time Complexity: O(log(n))" }, { "code": null, "e": 5894, "s": 5450, "text": "Auxiliary Space: O(1)This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5900, "s": 5894, "text": "jit_t" }, { "code": null, "e": 5913, "s": 5900, "text": "Mithun Kumar" }, { "code": null, "e": 5929, "s": 5913, "text": "subhammahato348" }, { "code": null, "e": 5945, "s": 5929, "text": "mayanktyagi1709" }, { "code": null, "e": 5958, "s": 5945, "text": "Mathematical" }, { "code": null, "e": 5971, "s": 5958, "text": "Mathematical" }, { "code": null, "e": 6069, "s": 5971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6093, "s": 6069, "text": "Merge two sorted arrays" }, { "code": null, "e": 6114, "s": 6093, "text": "Operators in C / C++" }, { "code": null, "e": 6128, "s": 6114, "text": "Prime Numbers" }, { "code": null, "e": 6150, "s": 6128, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6192, "s": 6150, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6245, "s": 6192, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 6277, "s": 6245, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 6314, "s": 6277, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 6341, "s": 6314, "text": "Modulo 10^9+7 (1000000007)" } ]
gcd() in Python
30 May, 2022 The Highest Common Factor (HCF), also called gcd, can be computed in python using a single function offered by math module and hence can make tasks easier in many situations. Python3 # Python code to demonstrate naive# method to compute gcd ( recursion ) def hcfnaive(a, b): if(b == 0): return abs(a) else: return hcfnaive(b, a % b) a = 60b = 48 # prints 12print("The gcd of 60 and 48 is : ", end="")print(hcfnaive(60, 48)) The gcd of 60 and 48 is : 12 Python3 # Python code to demonstrate naive# method to compute gcd ( Loops ) def computeGCD(x, y): if x > y: small = y else: small = x for i in range(1, small + 1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd a = 60b = 48 # prints 12print ("The gcd of 60 and 48 is : ", end="")print (computeGCD(60,48)) The gcd of 60 and 48 is : 12 Python3 # Python code to demonstrate naive# method to compute gcd ( Euclidean algo ) def computeGCD(x, y): while(y): x, y = y, x % y return abs(x) a = 60b = 48 # prints 12print ("The gcd of 60 and 48 is : ",end="")print (computeGCD(60, 48)) Output: The gcd of 60 and 48 is : 12 Both numbers are 0, gcd is 0 If only either number is Not a number, Type Error is raised. lwchkg Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2022" }, { "code": null, "e": 227, "s": 52, "text": "The Highest Common Factor (HCF), also called gcd, can be computed in python using a single function offered by math module and hence can make tasks easier in many situations." }, { "code": null, "e": 235, "s": 227, "text": "Python3" }, { "code": "# Python code to demonstrate naive# method to compute gcd ( recursion ) def hcfnaive(a, b): if(b == 0): return abs(a) else: return hcfnaive(b, a % b) a = 60b = 48 # prints 12print(\"The gcd of 60 and 48 is : \", end=\"\")print(hcfnaive(60, 48))", "e": 496, "s": 235, "text": null }, { "code": null, "e": 526, "s": 496, "text": "The gcd of 60 and 48 is : 12\n" }, { "code": null, "e": 534, "s": 526, "text": "Python3" }, { "code": "# Python code to demonstrate naive# method to compute gcd ( Loops ) def computeGCD(x, y): if x > y: small = y else: small = x for i in range(1, small + 1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd a = 60b = 48 # prints 12print (\"The gcd of 60 and 48 is : \", end=\"\")print (computeGCD(60,48))", "e": 896, "s": 534, "text": null }, { "code": null, "e": 926, "s": 896, "text": "The gcd of 60 and 48 is : 12\n" }, { "code": null, "e": 934, "s": 926, "text": "Python3" }, { "code": "# Python code to demonstrate naive# method to compute gcd ( Euclidean algo ) def computeGCD(x, y): while(y): x, y = y, x % y return abs(x) a = 60b = 48 # prints 12print (\"The gcd of 60 and 48 is : \",end=\"\")print (computeGCD(60, 48))", "e": 1180, "s": 934, "text": null }, { "code": null, "e": 1188, "s": 1180, "text": "Output:" }, { "code": null, "e": 1217, "s": 1188, "text": "The gcd of 60 and 48 is : 12" }, { "code": null, "e": 1246, "s": 1217, "text": "Both numbers are 0, gcd is 0" }, { "code": null, "e": 1307, "s": 1246, "text": "If only either number is Not a number, Type Error is raised." }, { "code": null, "e": 1314, "s": 1307, "text": "lwchkg" }, { "code": null, "e": 1321, "s": 1314, "text": "Python" } ]
How to set the offset property for ScrollSpy in Bootstrap ? - GeeksforGeeks
08 Jul, 2020 Offset is a Bootstrap Scrollspy property wherein the user can specify the pixels to offset from top when calculating the position of scroll. It becomes useful when the user feels that either the navbar or the list changes the state early or when not needed while surfing. It is always a number and the default value is 10. The value can be changed through JavaScript or putting the data-offset value in the body tag. Syntax: Normal Declaration(body data-offset="") (body data-offset="") JavaScript Declaration$(document).ready(function(){ $('body').scrollspy({target: " ", offset: }); }); $(document).ready(function(){ $('body').scrollspy({target: " ", offset: }); }); Example 1: This example describes the bootstrap navbar where four sections have been used and the offset property is set at 60 using JavaScript. <!DOCTYPE html><html> <head> <title>Bootstrap offset property</title> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"> </script> <style> body { position: relative; } #section1 { padding-top: 50px; height: 600px; background-color: #32CD32; } #section2 { padding-top: 50px; height: 600px; background-color: #FFFF00; } #section3 { padding-top: 50px; height: 600px; background-color: #00FF00; } #section4 { padding-top: 50px; height: 600px; background-color: #FF0000; } </style></head> <body> <nav class="navbar navbar-dark bg-success navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> GeeksforGeeks </a> </div> <div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="#section1">Section 1</a></li> <li><a href="#section2">Section 2</a></li> <li><a href="#section3">Section 3</a></li> <li><a href="#section4">Section 4</a></li> </ul> </div> </div> </div> </nav> <div id="section1" class="container-fluid"> <h1>Section 1</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id="section2" class="container-fluid"> <h1>Section 2</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id="section3" class="container-fluid"> <h1>Section 3</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id="section4" class="container-fluid"> <h1>Section 4</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <script> $(document).ready(function () { $('body').scrollspy({ target: ".navbar", offset: 50 }); }); </script></body> </html> Output: Example 2: The example describes bootstrap list-group where three sections have been used and the offset property is set at 15 in the body tag. <!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 ScrollSpy</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> body { position: relative; /* required */ } .list-group { position: sticky; top: 20px; } </style></head> <body data-spy="scroll" data-offset="20" data-target="#myScrollspy"> <div class="container"> <h1>Bootstrap Scrollspy</h1> <br> <div class="row"> <div class="col-sm-3" id="myScrollspy"> <div class="list-group"> <a class="list-group-item list-group-item-action active" href="#section1">Section One </a> <a class="list-group-item list-group-item-action" href="#section2">Section Two </a> <a class="list-group-item list-group-item-action" href="#section3">Section Three </a> </div> </div> <div class="col-sm-9"> <div id="section1"> <h2>Section One</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> <div id="section2"> <h2>Section Two</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> <div id="section3"> <h2>Section Three</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> </div> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-Misc CSS-Misc HTML-Misc Picked Bootstrap CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to change the background color of the active nav-item? How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26029, "s": 26001, "text": "\n08 Jul, 2020" }, { "code": null, "e": 26446, "s": 26029, "text": "Offset is a Bootstrap Scrollspy property wherein the user can specify the pixels to offset from top when calculating the position of scroll. It becomes useful when the user feels that either the navbar or the list changes the state early or when not needed while surfing. It is always a number and the default value is 10. The value can be changed through JavaScript or putting the data-offset value in the body tag." }, { "code": null, "e": 26454, "s": 26446, "text": "Syntax:" }, { "code": null, "e": 26494, "s": 26454, "text": "Normal Declaration(body data-offset=\"\")" }, { "code": null, "e": 26516, "s": 26494, "text": "(body data-offset=\"\")" }, { "code": null, "e": 26621, "s": 26516, "text": "JavaScript Declaration$(document).ready(function(){\n $('body').scrollspy({target: \" \", offset: });\n});\n" }, { "code": null, "e": 26704, "s": 26621, "text": "$(document).ready(function(){\n $('body').scrollspy({target: \" \", offset: });\n});\n" }, { "code": null, "e": 26849, "s": 26704, "text": "Example 1: This example describes the bootstrap navbar where four sections have been used and the offset property is set at 60 using JavaScript." }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap offset property</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\"> </script> <style> body { position: relative; } #section1 { padding-top: 50px; height: 600px; background-color: #32CD32; } #section2 { padding-top: 50px; height: 600px; background-color: #FFFF00; } #section3 { padding-top: 50px; height: 600px; background-color: #00FF00; } #section4 { padding-top: 50px; height: 600px; background-color: #FF0000; } </style></head> <body> <nav class=\"navbar navbar-dark bg-success navbar-fixed-top\"> <div class=\"container-fluid\"> <div class=\"navbar-header\"> <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#myNavbar\"> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"navbar-brand\" href=\"#\"> GeeksforGeeks </a> </div> <div> <div class=\"collapse navbar-collapse\" id=\"myNavbar\"> <ul class=\"nav navbar-nav\"> <li><a href=\"#section1\">Section 1</a></li> <li><a href=\"#section2\">Section 2</a></li> <li><a href=\"#section3\">Section 3</a></li> <li><a href=\"#section4\">Section 4</a></li> </ul> </div> </div> </div> </nav> <div id=\"section1\" class=\"container-fluid\"> <h1>Section 1</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id=\"section2\" class=\"container-fluid\"> <h1>Section 2</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id=\"section3\" class=\"container-fluid\"> <h1>Section 3</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <div id=\"section4\" class=\"container-fluid\"> <h1>Section 4</h1> <hr> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <script> $(document).ready(function () { $('body').scrollspy({ target: \".navbar\", offset: 50 }); }); </script></body> </html>", "e": 32119, "s": 26849, "text": null }, { "code": null, "e": 32127, "s": 32119, "text": "Output:" }, { "code": null, "e": 32271, "s": 32127, "text": "Example 2: The example describes bootstrap list-group where three sections have been used and the offset property is set at 15 in the body tag." }, { "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 ScrollSpy</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> body { position: relative; /* required */ } .list-group { position: sticky; top: 20px; } </style></head> <body data-spy=\"scroll\" data-offset=\"20\" data-target=\"#myScrollspy\"> <div class=\"container\"> <h1>Bootstrap Scrollspy</h1> <br> <div class=\"row\"> <div class=\"col-sm-3\" id=\"myScrollspy\"> <div class=\"list-group\"> <a class=\"list-group-item list-group-item-action active\" href=\"#section1\">Section One </a> <a class=\"list-group-item list-group-item-action\" href=\"#section2\">Section Two </a> <a class=\"list-group-item list-group-item-action\" href=\"#section3\">Section Three </a> </div> </div> <div class=\"col-sm-9\"> <div id=\"section1\"> <h2>Section One</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> <div id=\"section2\"> <h2>Section Two</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> <div id=\"section3\"> <h2>Section Three</h2> <p> GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. GeeksforGeeks is a computer science portal. It was created with a goal in mind to provide well written, well thought and well explained solutions for selected questions. The core team of five super geeks constituting of technology lovers and computer science enthusiasts have been constantly working in this direction. </p> </div> <hr> </div> </div> </div></body> </html>", "e": 38641, "s": 32271, "text": null }, { "code": null, "e": 38649, "s": 38641, "text": "Output:" }, { "code": null, "e": 38786, "s": 38649, "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": 38801, "s": 38786, "text": "Bootstrap-Misc" }, { "code": null, "e": 38810, "s": 38801, "text": "CSS-Misc" }, { "code": null, "e": 38820, "s": 38810, "text": "HTML-Misc" }, { "code": null, "e": 38827, "s": 38820, "text": "Picked" }, { "code": null, "e": 38837, "s": 38827, "text": "Bootstrap" }, { "code": null, "e": 38841, "s": 38837, "text": "CSS" }, { "code": null, "e": 38846, "s": 38841, "text": "HTML" }, { "code": null, "e": 38863, "s": 38846, "text": "Web Technologies" }, { "code": null, "e": 38890, "s": 38863, "text": "Web technologies Questions" }, { "code": null, "e": 38895, "s": 38890, "text": "HTML" }, { "code": null, "e": 38993, "s": 38895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39034, "s": 38993, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 39097, "s": 39034, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 39130, "s": 39097, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 39189, "s": 39130, "text": "How to change the background color of the active nav-item?" }, { "code": null, "e": 39238, "s": 39189, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 39300, "s": 39238, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39350, "s": 39300, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39398, "s": 39350, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39456, "s": 39398, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Proving elements of a finite group is finite - GeeksforGeeks
17 Mar, 2021 To Prove : The order of every element of a finite group is finite and is less than or equal to the order of the group. Proof : Suppose G is a finite group, the composition being denoted multiplicatively. Suppose a ∈ G, consider all positive integral powers of a i.e., a, a2, a3, ...... All these are elements of G, by closure axiom. Since G has a finite number of elements, therefore all these integral powers of a cannot be distinct elements of G. Suppose, ar = as where r > s Now ar = as => ar . a-s = as . a-s (multiplying both sides by a-s ) => ar . a-s = a0 ( as-s = a0) => ar . a-s = e => am = e, where m = r - s Since r > s Therefore, ‘m’ is a positive integer. Hence, there exists a positive integer m such that am = e. Now we know that every set of positive integers has the least member. Therefore, the set of all those positive integers m such that am = e has the least members, say n. Thus, there exists the least positive integer n such that an = e. Therefore, the order of a, o(a) is finite. Now to prove that o(a) ≤ o(G). Suppose, o(a) = n, where n > o(G). Since a ∈ G, therefore by closure property a, a2, .... an are elements of G. No two of these are equal. For if possible, let ar = as, 1 ≤ s < r ≤ n. Then, ar-s = e Since 0 < r - s < n Therefore, ar-s = e implies that the order of a is less than n. This is a contradiction. Hence, a, a2,... an are n distinct elements of G. Since n > o(G), therefore this is not possible. Hence, we must have o(a) ≤ o(G). Therefore, it is proved that The order of every element (a, o(a)) of a finite group (G) is finite and is less than or equal to the order of the group(i.e. o(a) ≤ o(g) ). Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Difference between Propositional Logic and Predicate Logic Logic Notations in LaTeX Univariate, Bivariate and Multivariate data and its analysis Z-test Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26137, "s": 26109, "text": "\n17 Mar, 2021" }, { "code": null, "e": 26257, "s": 26137, "text": "To Prove : The order of every element of a finite group is finite and is less than or equal to the order of the group. " }, { "code": null, "e": 26588, "s": 26257, "text": "Proof : Suppose G is a finite group, the composition being denoted multiplicatively. Suppose a ∈ G, consider all positive integral powers of a i.e., a, a2, a3, ...... All these are elements of G, by closure axiom. Since G has a finite number of elements, therefore all these integral powers of a cannot be distinct elements of G." }, { "code": null, "e": 26597, "s": 26588, "text": "Suppose," }, { "code": null, "e": 26620, "s": 26597, "text": "ar = as where r > s" }, { "code": null, "e": 26647, "s": 26620, "text": "Now " }, { "code": null, "e": 26819, "s": 26647, "text": "ar = as \n=> ar . a-s = as . a-s (multiplying both sides by a-s )\n=> ar . a-s = a0 ( as-s = a0)\n=> ar . a-s = e \n=> am = e, where m = r - s " }, { "code": null, "e": 26829, "s": 26819, "text": "Since " }, { "code": null, "e": 26835, "s": 26829, "text": "r > s" }, { "code": null, "e": 26933, "s": 26835, "text": "Therefore, ‘m’ is a positive integer. Hence, there exists a positive integer m such that am = e. " }, { "code": null, "e": 27161, "s": 26933, "text": "Now we know that every set of positive integers has the least member. Therefore, the set of all those positive integers m such that am = e has the least members, say n. Thus, there exists the least positive integer n such that " }, { "code": null, "e": 27170, "s": 27161, "text": "an = e. " }, { "code": null, "e": 27245, "s": 27170, "text": "Therefore, the order of a, o(a) is finite. Now to prove that o(a) ≤ o(G). " }, { "code": null, "e": 27254, "s": 27245, "text": "Suppose," }, { "code": null, "e": 27281, "s": 27254, "text": "o(a) = n, where n > o(G). " }, { "code": null, "e": 27436, "s": 27281, "text": "Since a ∈ G, therefore by closure property a, a2, .... an are elements of G. No two of these are equal. For if possible, let ar = as, 1 ≤ s < r ≤ n. Then," }, { "code": null, "e": 27445, "s": 27436, "text": "ar-s = e" }, { "code": null, "e": 27452, "s": 27445, "text": "Since " }, { "code": null, "e": 27466, "s": 27452, "text": "0 < r - s < n" }, { "code": null, "e": 27478, "s": 27466, "text": "Therefore, " }, { "code": null, "e": 27532, "s": 27478, "text": "ar-s = e implies that the order of a is less than n. " }, { "code": null, "e": 27689, "s": 27532, "text": "This is a contradiction. Hence, a, a2,... an are n distinct elements of G. Since n > o(G), therefore this is not possible. Hence, we must have o(a) ≤ o(G). " }, { "code": null, "e": 27859, "s": 27689, "text": "Therefore, it is proved that The order of every element (a, o(a)) of a finite group (G) is finite and is less than or equal to the order of the group(i.e. o(a) ≤ o(g) )." }, { "code": null, "e": 27883, "s": 27859, "text": "Engineering Mathematics" }, { "code": null, "e": 27891, "s": 27883, "text": "GATE CS" }, { "code": null, "e": 27989, "s": 27891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28010, "s": 27989, "text": "Activation Functions" }, { "code": null, "e": 28069, "s": 28010, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 28094, "s": 28069, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 28155, "s": 28094, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 28162, "s": 28155, "text": "Z-test" }, { "code": null, "e": 28182, "s": 28162, "text": "Layers of OSI Model" }, { "code": null, "e": 28206, "s": 28182, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28219, "s": 28206, "text": "TCP/IP Model" }, { "code": null, "e": 28246, "s": 28219, "text": "Types of Operating Systems" } ]
Python | time.mktime() method - GeeksforGeeks
17 Sep, 2019 time.mktime() method of Time module is used to convert a time.struct_time object or a tuple containing 9 elements corresponding to time.struct_time object to time in seconds passed since epoch in local time. This method is the inverse function of time.localtime() which converts the time expressed in seconds since the epoch to a time.struct_time object in local time. Following are the values present in time.struct_time object: Note: The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0). Syntax: time.mktime(t) Parameter:t : A time.struct_time object or a tuple containing 9 elements corresponding to time.struct_time object Return type: This method returns a float value which represents the time expressed in seconds since the epoch. Code #1: Use of time.mktime() method # Python program to explain time.mktime() method # importing time module import time # time.gmtime() method will returns# a time.struct_time object in UTC# for the time expressed in seconds# since the epochseconds = 1000000obj1 = time.gmtime(seconds) # Print time.struct_time object (in UTC)print(obj1) # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj1) # Print the local time in secondsprint("\nLocal time (in seconds):", time_sec) # time.strptime() method parse # a string representing a time# according to the given format# and returns a time.struct_time object # Time string t = "14 Sep 2019 10:50:00" # Parse the time string using# time.strptime() methodobj2 = time.strptime(t, "% d % b % Y % H:% M:% S") # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj2) # Print the local time in secondsprint("\nLocal time (in seconds):", time_sec) time.struct_time(tm_year=1970, tm_mon=1, tm_mday=12, tm_hour=13, tm_min=46, tm_sec=40, tm_wday=0, tm_yday=12, tm_isdst=0) Local time (in seconds): 980200.0 Local time (in seconds): 1568438400.0 Code #2: If parameter is a tuple # Python program to explain time.mktime() method # importing time module import time # A tuple containing 9 elements# corresponding to time.struct_time object# for example: consider the below object# time.struct_time(tm_year = 2019, tm_mon = 9, tm_mday = 13, # tm_hour = 1, tm_min = 30, tm_sec = 26, tm_wday = 4,# tm_yday = 256, tm_isdst = 0) # Tuple corresponding to above # time.struct_time object will betup = (2019, 9, 13, 1, 30, 26, 4, 256, 0) # Convert the above specified tuple# to local time expressed in seconds# since the epoch # using time.mktime() methodtime_sec = time.mktime(tup) # Print the timeprint("Local Time (in seconds since the epoch):", time_sec) Local Time (in seconds since the epoch): 1568318426.0 Code #3: To show time.mktime() method is inverse function of time.localtime() method # Python program to explain time.mktime() method # importing time module import time # Get the current time# expressed in seconds # since the epoch using# time.time() methodcurr_time = time.time() # Print the value# returned by time.time() methodprint("Current time (in seconds since the epoch):", curr_time) # Convert the time expressed in seconds# since the epoch to# a time.struct_time object# in local time using# time.localtime() method obj = time.localtime(curr_time) # Print the time.struct_time objectprint("\ntime.struct_time object:")print(obj, "\n") # Convert the time.struct_time object# back to the time expressed# in seconds since the epoch# in local time using# time.mktime() methodtime_sec = time.mktime(obj) # Print the timeprint("Time (in seconds since the epoch):", time_sec) Current time (in seconds since the epoch): 1568318426.2286296 time.struct_time object: time.struct_time(tm_year=2019, tm_mon=9, tm_mday=13, tm_hour=1, tm_min=30, tm_sec=26, tm_wday=4, tm_yday=256, tm_isdst=0) Time (in seconds since the epoch): 1568318426.0 References: https://docs.python.org/3/library/time.html#time.mktime python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Sep, 2019" }, { "code": null, "e": 25745, "s": 25537, "text": "time.mktime() method of Time module is used to convert a time.struct_time object or a tuple containing 9 elements corresponding to time.struct_time object to time in seconds passed since epoch in local time." }, { "code": null, "e": 25906, "s": 25745, "text": "This method is the inverse function of time.localtime() which converts the time expressed in seconds since the epoch to a time.struct_time object in local time." }, { "code": null, "e": 25967, "s": 25906, "text": "Following are the values present in time.struct_time object:" }, { "code": null, "e": 26276, "s": 25967, "text": "Note: The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0)." }, { "code": null, "e": 26299, "s": 26276, "text": "Syntax: time.mktime(t)" }, { "code": null, "e": 26413, "s": 26299, "text": "Parameter:t : A time.struct_time object or a tuple containing 9 elements corresponding to time.struct_time object" }, { "code": null, "e": 26524, "s": 26413, "text": "Return type: This method returns a float value which represents the time expressed in seconds since the epoch." }, { "code": null, "e": 26561, "s": 26524, "text": "Code #1: Use of time.mktime() method" }, { "code": "# Python program to explain time.mktime() method # importing time module import time # time.gmtime() method will returns# a time.struct_time object in UTC# for the time expressed in seconds# since the epochseconds = 1000000obj1 = time.gmtime(seconds) # Print time.struct_time object (in UTC)print(obj1) # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj1) # Print the local time in secondsprint(\"\\nLocal time (in seconds):\", time_sec) # time.strptime() method parse # a string representing a time# according to the given format# and returns a time.struct_time object # Time string t = \"14 Sep 2019 10:50:00\" # Parse the time string using# time.strptime() methodobj2 = time.strptime(t, \"% d % b % Y % H:% M:% S\") # Convert the time.struct_time# object to local time expressed in# seconds since the epoch# using time.mktime() methodtime_sec = time.mktime(obj2) # Print the local time in secondsprint(\"\\nLocal time (in seconds):\", time_sec)", "e": 27611, "s": 26561, "text": null }, { "code": null, "e": 27808, "s": 27611, "text": "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=12, tm_hour=13, tm_min=46,\ntm_sec=40, tm_wday=0, tm_yday=12, tm_isdst=0)\n\nLocal time (in seconds): 980200.0\n\nLocal time (in seconds): 1568438400.0\n" }, { "code": null, "e": 27841, "s": 27808, "text": "Code #2: If parameter is a tuple" }, { "code": "# Python program to explain time.mktime() method # importing time module import time # A tuple containing 9 elements# corresponding to time.struct_time object# for example: consider the below object# time.struct_time(tm_year = 2019, tm_mon = 9, tm_mday = 13, # tm_hour = 1, tm_min = 30, tm_sec = 26, tm_wday = 4,# tm_yday = 256, tm_isdst = 0) # Tuple corresponding to above # time.struct_time object will betup = (2019, 9, 13, 1, 30, 26, 4, 256, 0) # Convert the above specified tuple# to local time expressed in seconds# since the epoch # using time.mktime() methodtime_sec = time.mktime(tup) # Print the timeprint(\"Local Time (in seconds since the epoch):\", time_sec)", "e": 28522, "s": 27841, "text": null }, { "code": null, "e": 28577, "s": 28522, "text": "Local Time (in seconds since the epoch): 1568318426.0\n" }, { "code": null, "e": 28662, "s": 28577, "text": "Code #3: To show time.mktime() method is inverse function of time.localtime() method" }, { "code": "# Python program to explain time.mktime() method # importing time module import time # Get the current time# expressed in seconds # since the epoch using# time.time() methodcurr_time = time.time() # Print the value# returned by time.time() methodprint(\"Current time (in seconds since the epoch):\", curr_time) # Convert the time expressed in seconds# since the epoch to# a time.struct_time object# in local time using# time.localtime() method obj = time.localtime(curr_time) # Print the time.struct_time objectprint(\"\\ntime.struct_time object:\")print(obj, \"\\n\") # Convert the time.struct_time object# back to the time expressed# in seconds since the epoch# in local time using# time.mktime() methodtime_sec = time.mktime(obj) # Print the timeprint(\"Time (in seconds since the epoch):\", time_sec) ", "e": 29476, "s": 28662, "text": null }, { "code": null, "e": 29737, "s": 29476, "text": "Current time (in seconds since the epoch): 1568318426.2286296\n\ntime.struct_time object:\ntime.struct_time(tm_year=2019, tm_mon=9, tm_mday=13, tm_hour=1, tm_min=30,\ntm_sec=26, tm_wday=4, tm_yday=256, tm_isdst=0) \n\nTime (in seconds since the epoch): 1568318426.0\n" }, { "code": null, "e": 29805, "s": 29737, "text": "References: https://docs.python.org/3/library/time.html#time.mktime" }, { "code": null, "e": 29820, "s": 29805, "text": "python-utility" }, { "code": null, "e": 29827, "s": 29820, "text": "Python" }, { "code": null, "e": 29925, "s": 29827, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29957, "s": 29925, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29999, "s": 29957, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30041, "s": 29999, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30068, "s": 30041, "text": "Python Classes and Objects" }, { "code": null, "e": 30124, "s": 30068, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30146, "s": 30124, "text": "Defaultdict in Python" }, { "code": null, "e": 30185, "s": 30146, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30216, "s": 30185, "text": "Python | os.path.join() method" }, { "code": null, "e": 30245, "s": 30216, "text": "Create a directory in Python" } ]
Dynamic ImageButton in Kotlin - GeeksforGeeks
28 Mar, 2022 Android ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton etc. We can add an image to the button simply by using attribute android:src in activity_main.xml file or by using setImageResource() method. In android, we can create ImageButton control in two ways either manually or programmatically. First we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this article, we will create the ImageButton programmatically in Kotlin file. In this file, we will add only the EditText and set attributes for both of them to access into the Kotlin file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout" android:gravity="center"> <EditText android:id="@+id/Num1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint= "Enter first number"/> <EditText android:id="@+id/Num2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint= "Enter second number"/> </LinearLayout> Modify the strings.xml file to write the name of the application XML <resources> <string name="app_name">DynamicImageButtonInKotlin</string></resources> We will declare a variable imgBtn to create ImageButton. val imgBtn = ImageButton(this) then, set the image resource for the button using imgBtn.setImageResource(R.drawable.ic_clear_black_24dp) In the end, add the button into LinearLayout using val linearLayout = findViewById(R.id.linear_layout) // Adding ImageButton in LinearLayout linearLayout.addView(imgBtn) Other process similar to manually adding the Image Button in the layout. Kotlin package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport android.view.ViewGroupimport androidx.appcompat.app.AppCompatActivityimport android.widget.EditTextimport android.widget.ImageButtonimport android.widget.LinearLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val num1 = findViewById<EditText>(R.id.Num1) val num2 = findViewById<EditText>(R.id.Num2) val imgBtn = ImageButton(this) imgBtn.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) imgBtn.setImageResource(R.drawable.ic_clear_black_24dp) val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) // Adding ImageButton in LinearLayout linearLayout.addView(imgBtn) imgBtn.setOnClickListener { if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) { Toast.makeText(applicationContext, "Enter both numbers", Toast.LENGTH_SHORT).show() } else { val num1 = Integer.parseInt(num1.text.toString()) val num2 = Integer.parseInt(num2.text.toString()) Toast.makeText(applicationContext, "Multiplication of the numbers = " + (num1 * num2), Toast.LENGTH_SHORT).show() } } }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest> ayushpandey3july Android-Button Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Services in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 25257, "s": 25229, "text": "\n28 Mar, 2022" }, { "code": null, "e": 25559, "s": 25257, "text": "Android ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton etc." }, { "code": null, "e": 25696, "s": 25559, "text": "We can add an image to the button simply by using attribute android:src in activity_main.xml file or by using setImageResource() method." }, { "code": null, "e": 25791, "s": 25696, "text": "In android, we can create ImageButton control in two ways either manually or programmatically." }, { "code": null, "e": 25851, "s": 25791, "text": "First we create a new project by following the below steps:" }, { "code": null, "e": 26060, "s": 25851, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 26100, "s": 26060, "text": "Click on File, then New => New Project." }, { "code": null, "e": 26157, "s": 26100, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 26222, "s": 26157, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 26272, "s": 26222, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 26353, "s": 26272, "text": "In this article, we will create the ImageButton programmatically in Kotlin file." }, { "code": null, "e": 26465, "s": 26353, "text": "In this file, we will add only the EditText and set attributes for both of them to access into the Kotlin file." }, { "code": null, "e": 26469, "s": 26465, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\" android:gravity=\"center\"> <EditText android:id=\"@+id/Num1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint= \"Enter first number\"/> <EditText android:id=\"@+id/Num2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint= \"Enter second number\"/> </LinearLayout>", "e": 27175, "s": 26469, "text": null }, { "code": null, "e": 27240, "s": 27175, "text": "Modify the strings.xml file to write the name of the application" }, { "code": null, "e": 27244, "s": 27240, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">DynamicImageButtonInKotlin</string></resources>", "e": 27331, "s": 27244, "text": null }, { "code": null, "e": 27388, "s": 27331, "text": "We will declare a variable imgBtn to create ImageButton." }, { "code": null, "e": 27420, "s": 27388, "text": " val imgBtn = ImageButton(this)" }, { "code": null, "e": 27470, "s": 27420, "text": "then, set the image resource for the button using" }, { "code": null, "e": 27526, "s": 27470, "text": "imgBtn.setImageResource(R.drawable.ic_clear_black_24dp)" }, { "code": null, "e": 27577, "s": 27526, "text": "In the end, add the button into LinearLayout using" }, { "code": null, "e": 27701, "s": 27577, "text": "val linearLayout = findViewById(R.id.linear_layout)\n // Adding ImageButton in LinearLayout\n linearLayout.addView(imgBtn)\n" }, { "code": null, "e": 27774, "s": 27701, "text": "Other process similar to manually adding the Image Button in the layout." }, { "code": null, "e": 27781, "s": 27774, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport android.view.ViewGroupimport androidx.appcompat.app.AppCompatActivityimport android.widget.EditTextimport android.widget.ImageButtonimport android.widget.LinearLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val num1 = findViewById<EditText>(R.id.Num1) val num2 = findViewById<EditText>(R.id.Num2) val imgBtn = ImageButton(this) imgBtn.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) imgBtn.setImageResource(R.drawable.ic_clear_black_24dp) val linearLayout = findViewById<LinearLayout>(R.id.linear_layout) // Adding ImageButton in LinearLayout linearLayout.addView(imgBtn) imgBtn.setOnClickListener { if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) { Toast.makeText(applicationContext, \"Enter both numbers\", Toast.LENGTH_SHORT).show() } else { val num1 = Integer.parseInt(num1.text.toString()) val num2 = Integer.parseInt(num2.text.toString()) Toast.makeText(applicationContext, \"Multiplication of the numbers = \" + (num1 * num2), Toast.LENGTH_SHORT).show() } } }}", "e": 29340, "s": 27781, "text": null }, { "code": null, "e": 29344, "s": 29340, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 29999, "s": 29344, "text": null }, { "code": null, "e": 30018, "s": 30001, "text": "ayushpandey3july" }, { "code": null, "e": 30033, "s": 30018, "text": "Android-Button" }, { "code": null, "e": 30048, "s": 30033, "text": "Kotlin Android" }, { "code": null, "e": 30056, "s": 30048, "text": "Android" }, { "code": null, "e": 30063, "s": 30056, "text": "Kotlin" }, { "code": null, "e": 30071, "s": 30063, "text": "Android" }, { "code": null, "e": 30169, "s": 30071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30227, "s": 30169, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 30270, "s": 30227, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30308, "s": 30270, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30341, "s": 30308, "text": "Services in Android with Example" }, { "code": null, "e": 30372, "s": 30341, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 30415, "s": 30372, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 30434, "s": 30415, "text": "Android UI Layouts" }, { "code": null, "e": 30447, "s": 30434, "text": "Kotlin Array" }, { "code": null, "e": 30480, "s": 30447, "text": "Services in Android with Example" } ]
JavaScript Course | Data Types in JavaScript - GeeksforGeeks
29 Apr, 2019 Previous article: JavaScript Course | Variables in JavaScript Datatypes in JavaScript There are majorly two types of languages. First, one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types.Example: C, C++, Java. // Java(Statically typed)// variable x is of type int and it// will not store any other type.int x = 5; // type string and will only accept string valuesstring y = 'abc'; Other, Dynamically typed languages: These languages can receive different data types over time. For example- Ruby, Python, JavaScript etc. // Javascript(Dynamically typed)var x = 5; // can store an integervar name = 'string'; // can also store a string. JavaScript is dynamically typed (also called loosely typed) scripting language. That is, in javascript variables can receive different data types over time. Datatypes are basically typed of data that can be used and manipulated in a program. A variable in JavaScript can contain any data. This means that a variable at one time can be a number and at another be a string. The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are Primitive(predefined). Numbers: 5, 6.5, 7 etc. String: “Hello GeeksforGeeks” etc. Boolean: Represent a logical entity and can have two values: true or false. Null: This type has only one value : null. Undefined: A variable that has not been assigned a value is undefined. Object: It is the most important data-type and forms the building blocks for modern JavaScript. We will learn about these data types in details in further articles. A numberThe number type in javascript contains both integer and floating point numbers. Besides these numbers, we also have some ‘special-numbers’ in javascript that are: ‘Infinity’, ‘-Infinity’ and ‘NaN’. The Infinity basically represents the mathematical ‘?’. The ‘NaN’ denotes a computational error. let num = 2; // integer let num2 = 1.3; // floating point number let num3 = Infinity; // Infinity let num4 = 'something here too'/2; // NaN StringA String in javascript is basically a series of characters that are surrounded by quotes. There are three types of quotes in Javascript, which are: let str = "Hello There"; let str2 = 'Single quotes works fine'; let phrase = `can embed ${str}`; There’s no difference between ‘single’ and “double” quotes in javascript. Backticks provide extra functionality as with the help of them we can embed variables inside them. let name = "Mukul"; // embed a variable alert( `Hello, ${name}!` ); // Hello, Mukul! A BooleanThe boolean type has only two values: true and false. This data type is used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”. let isCoding = true; // yes let isOld = false; // no A nullThe special null value does not belong to any of the default data types. It forms a separate type of its own which contains only the null value: let age = null; The ‘null’ data type basically defines a special value which represents ‘nothing’, ’empty’ or ‘value unknown’. UndefinedJust like null, Undefined makes its own type. The meaning of undefined is ‘value is not assigned’. let x; console.log(x); // undefined ObjectObjects are not primitive in nature and a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to store keyed collections of various data and more complex entities.We can create objects in multiple ways. One is by making use of figure brackets {...} with an optional list of properties. The properties of an object are in the form of ‘key: value’ pair. Another way is to make use of the ‘new’ keyword.An empty Object can be created using given below syntax. let person = new Object(); // "object constructor" syntax let person = {}; // "object literal" syntax Both these method are correct, though it’s totally your call what to choose. We can also put properties inside an Object like: <script>// an objectlet person = { name: "Mukul", // by key "name" store value "Mukul" age: 22 // by key "age" store value 22};</script> Next article: JavaScript Course | Operators in JavaScript aayushimittal3 JavaScript-Course 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 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 append HTML code to a div using JavaScript ? 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": 25925, "s": 25897, "text": "\n29 Apr, 2019" }, { "code": null, "e": 25987, "s": 25925, "text": "Previous article: JavaScript Course | Variables in JavaScript" }, { "code": null, "e": 26011, "s": 25987, "text": "Datatypes in JavaScript" }, { "code": null, "e": 26290, "s": 26011, "text": "There are majorly two types of languages. First, one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types.Example: C, C++, Java." }, { "code": "// Java(Statically typed)// variable x is of type int and it// will not store any other type.int x = 5; // type string and will only accept string valuesstring y = 'abc'; ", "e": 26463, "s": 26290, "text": null }, { "code": null, "e": 26602, "s": 26463, "text": "Other, Dynamically typed languages: These languages can receive different data types over time. For example- Ruby, Python, JavaScript etc." }, { "code": "// Javascript(Dynamically typed)var x = 5; // can store an integervar name = 'string'; // can also store a string.", "e": 26717, "s": 26602, "text": null }, { "code": null, "e": 27089, "s": 26717, "text": "JavaScript is dynamically typed (also called loosely typed) scripting language. That is, in javascript variables can receive different data types over time. Datatypes are basically typed of data that can be used and manipulated in a program. A variable in JavaScript can contain any data. This means that a variable at one time can be a number and at another be a string." }, { "code": null, "e": 27206, "s": 27089, "text": "The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are Primitive(predefined)." }, { "code": null, "e": 27230, "s": 27206, "text": "Numbers: 5, 6.5, 7 etc." }, { "code": null, "e": 27265, "s": 27230, "text": "String: “Hello GeeksforGeeks” etc." }, { "code": null, "e": 27341, "s": 27265, "text": "Boolean: Represent a logical entity and can have two values: true or false." }, { "code": null, "e": 27384, "s": 27341, "text": "Null: This type has only one value : null." }, { "code": null, "e": 27455, "s": 27384, "text": "Undefined: A variable that has not been assigned a value is undefined." }, { "code": null, "e": 27620, "s": 27455, "text": "Object: It is the most important data-type and forms the building blocks for modern JavaScript. We will learn about these data types in details in further articles." }, { "code": null, "e": 27923, "s": 27620, "text": "A numberThe number type in javascript contains both integer and floating point numbers. Besides these numbers, we also have some ‘special-numbers’ in javascript that are: ‘Infinity’, ‘-Infinity’ and ‘NaN’. The Infinity basically represents the mathematical ‘?’. The ‘NaN’ denotes a computational error." }, { "code": null, "e": 28065, "s": 27923, "text": "let num = 2; // integer \nlet num2 = 1.3; // floating point number\nlet num3 = Infinity; // Infinity\nlet num4 = 'something here too'/2; // NaN\n" }, { "code": null, "e": 28219, "s": 28065, "text": "StringA String in javascript is basically a series of characters that are surrounded by quotes. There are three types of quotes in Javascript, which are:" }, { "code": null, "e": 28317, "s": 28219, "text": "let str = \"Hello There\";\nlet str2 = 'Single quotes works fine';\nlet phrase = `can embed ${str}`;\n" }, { "code": null, "e": 28490, "s": 28317, "text": "There’s no difference between ‘single’ and “double” quotes in javascript. Backticks provide extra functionality as with the help of them we can embed variables inside them." }, { "code": null, "e": 28577, "s": 28490, "text": "let name = \"Mukul\";\n\n// embed a variable\nalert( `Hello, ${name}!` ); // Hello, Mukul!\n" }, { "code": null, "e": 28640, "s": 28577, "text": "A BooleanThe boolean type has only two values: true and false." }, { "code": null, "e": 28747, "s": 28640, "text": "This data type is used to store yes/no values: true means “yes, correct”, and false means “no, incorrect”." }, { "code": null, "e": 28803, "s": 28747, "text": " let isCoding = true; // yes\n let isOld = false; // no\n" }, { "code": null, "e": 28954, "s": 28803, "text": "A nullThe special null value does not belong to any of the default data types. It forms a separate type of its own which contains only the null value:" }, { "code": null, "e": 28970, "s": 28954, "text": "let age = null;" }, { "code": null, "e": 29081, "s": 28970, "text": "The ‘null’ data type basically defines a special value which represents ‘nothing’, ’empty’ or ‘value unknown’." }, { "code": null, "e": 29189, "s": 29081, "text": "UndefinedJust like null, Undefined makes its own type. The meaning of undefined is ‘value is not assigned’." }, { "code": null, "e": 29226, "s": 29189, "text": "let x;\nconsole.log(x); // undefined\n" }, { "code": null, "e": 29830, "s": 29226, "text": "ObjectObjects are not primitive in nature and a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to store keyed collections of various data and more complex entities.We can create objects in multiple ways. One is by making use of figure brackets {...} with an optional list of properties. The properties of an object are in the form of ‘key: value’ pair. Another way is to make use of the ‘new’ keyword.An empty Object can be created using given below syntax." }, { "code": null, "e": 29934, "s": 29830, "text": "let person = new Object(); // \"object constructor\" syntax\nlet person = {}; // \"object literal\" syntax\n" }, { "code": null, "e": 30061, "s": 29934, "text": "Both these method are correct, though it’s totally your call what to choose. We can also put properties inside an Object like:" }, { "code": "<script>// an objectlet person = { name: \"Mukul\", // by key \"name\" store value \"Mukul\" age: 22 // by key \"age\" store value 22};</script>", "e": 30213, "s": 30061, "text": null }, { "code": null, "e": 30271, "s": 30213, "text": "Next article: JavaScript Course | Operators in JavaScript" }, { "code": null, "e": 30286, "s": 30271, "text": "aayushimittal3" }, { "code": null, "e": 30304, "s": 30286, "text": "JavaScript-Course" }, { "code": null, "e": 30315, "s": 30304, "text": "JavaScript" }, { "code": null, "e": 30332, "s": 30315, "text": "Web Technologies" }, { "code": null, "e": 30430, "s": 30332, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30470, "s": 30430, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30515, "s": 30470, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30576, "s": 30515, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30648, "s": 30576, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30700, "s": 30648, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30740, "s": 30700, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30773, "s": 30740, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30818, "s": 30773, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30861, "s": 30818, "text": "How to fetch data from an API in ReactJS ?" } ]
Data Structures | Heap | Question 9 - GeeksforGeeks
28 Jun, 2021 In a binary max heap containing n numbers, the smallest element can be found in time (GATE CS 2006)(A) 0(n)(B) O(logn)(C) 0(loglogn)(D) 0(1)Answer: (A)Explanation: In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity will be O(n) 12 / \ / \ 8 7 / \ / \ / \ / \ 2 3 4 5 Quiz of this Question Data Structures Data Structures-Heap Heap Quizzes Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Linked List | Question 5 Data Structures | Tree Traversals | Question 4 Data Structures | Linked List | Question 6 Difference between Singly linked list and Doubly linked list Advantages and Disadvantages of Linked List Data Structures | Graph | Question 9 FIFO vs LIFO approach in Programming C program to implement Adjacency Matrix of a given Graph Data Structures | Stack | Question 1 Introduction to Data Structures
[ { "code": null, "e": 26061, "s": 26033, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26392, "s": 26061, "text": "In a binary max heap containing n numbers, the smallest element can be found in time (GATE CS 2006)(A) 0(n)(B) O(logn)(C) 0(loglogn)(D) 0(1)Answer: (A)Explanation: In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity will be O(n)" }, { "code": null, "e": 26507, "s": 26392, "text": " 12\n / \\\n / \\\n 8 7\n / \\ / \\\n / \\ / \\\n2 3 4 5" }, { "code": null, "e": 26529, "s": 26507, "text": "Quiz of this Question" }, { "code": null, "e": 26545, "s": 26529, "text": "Data Structures" }, { "code": null, "e": 26566, "s": 26545, "text": "Data Structures-Heap" }, { "code": null, "e": 26579, "s": 26566, "text": "Heap Quizzes" }, { "code": null, "e": 26595, "s": 26579, "text": "Data Structures" }, { "code": null, "e": 26611, "s": 26595, "text": "Data Structures" }, { "code": null, "e": 26709, "s": 26611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26752, "s": 26709, "text": "Data Structures | Linked List | Question 5" }, { "code": null, "e": 26799, "s": 26752, "text": "Data Structures | Tree Traversals | Question 4" }, { "code": null, "e": 26842, "s": 26799, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 26903, "s": 26842, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 26947, "s": 26903, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 26984, "s": 26947, "text": "Data Structures | Graph | Question 9" }, { "code": null, "e": 27021, "s": 26984, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 27078, "s": 27021, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 27115, "s": 27078, "text": "Data Structures | Stack | Question 1" } ]
Print the DFS traversal step-wise (Backtracking also) - GeeksforGeeks
14 Sep, 2021 Given a graph, the task is to print the DFS traversal of a graph which includes every step including the backtracking. 1st step:- 0 -> 1 2nd step:- 1 -> 5 3rd step:- 5 -> 1 (backtracking step) 4th step:- 1 -> 6... and so on till all the nodes are visited. Dfs step-wise(including backtracking) is: 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10 Note: In this above diagram the weight between the edges has just been added. It does not have any role in DFS-traversal. Approach: DFS with Backtracking will be used here. First, visit every node using DFS simultaneously and keep track of the previously used edge and the parent node. If a node comes where all the adjacent nodes have been visited, backtrack using the last used edge and print the nodes. Continue the steps and at every step, the parent node will become the present node. Continue the above steps to find the complete DFS traversal of the graph. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print the complete// DFS-traversal of graph// using back-tracking#include <bits/stdc++.h>using namespace std;const int N = 1000;vector<int> adj[N]; // Function to print the complete DFS-traversalvoid dfsUtil(int u, int node, bool visited[], vector<pair<int, int> > road_used, int parent, int it){ int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.push_back({ parent, u }); // Print the node cout << u << " "; // Check for not visited node and proceed with it. for (int x : adj[u]) { // call the DFs function if not visited if (!visited[x]) dfsUtil(x, node, visited, road_used, u, it + 1); } // Backtrack through the last // visited nodes for (auto y : road_used) if (y.second == u) dfsUtil(y.first, node, visited, road_used, u, it + 1);} // Function to call the DFS function// which prints the DFS-traversal stepwisevoid dfs(int node){ // Create a array of visited node bool visited[node]; // Vector to track last visited road vector<pair<int, int> > road_used; // Initialize all the node with false for (int i = 0; i < node; i++) visited[i] = false; // call the function dfsUtil(0, node, visited, road_used, -1, 0);} // Function to insert edges in Graphvoid insertEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Driver Codeint main(){ // number of nodes and edges in the graph int node = 11, edge = 13; // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); return 0;} // Java program to print the complete// DFS-traversal of graph// using back-trackingimport java.io.*;import java.util.*;class GFG{ static int N = 1000; static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); // Function to print the complete DFS-traversal static void dfsUtil(int u, int node, boolean visited[], ArrayList<ArrayList<Integer>> road_used, int parent, int it) { int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.add(new ArrayList<Integer>(Arrays.asList( parent, u ))); // Print the node System.out.print(u + " "); // Check for not visited node and proceed with it. for (int x : adj.get(u)) { // call the DFs function if not visited if (!visited[x]) { dfsUtil(x, node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for(int y = 0; y < road_used.size(); y++) { if(road_used.get(y).get(1) == u) { dfsUtil(road_used.get(y).get(0), node, visited,road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise static void dfs(int node) { // Create a array of visited node boolean[] visited = new boolean[node]; // Vector to track last visited road ArrayList<ArrayList<Integer>> road_used = new ArrayList<ArrayList<Integer>>(); // Initialize all the node with false for (int i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph static void insertEdge(int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // Driver Code public static void main (String[] args) { // number of nodes and edges in the graph int node = 11, edge = 13; for(int i = 0; i < N; i++) { adj.add(new ArrayList<Integer>()); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to print the# complete DFS-traversal of graph# using back-trackingN = 1000adj = [[] for i in range(N)] # Function to print the complete DFS-traversaldef dfsUtil(u, node,visited, road_used, parent, it): c = 0 # Check if all th node is visited # or not and count unvisited nodes for i in range(node): if (visited[i]): c += 1 # If all the node is visited return if (c == node): return # Mark not visited node as visited visited[u] = True # Track the current edge road_used.append([parent, u]) # Print the node print(u, end = " ") # Check for not visited node # and proceed with it. for x in adj[u]: # Call the DFs function # if not visited if (not visited[x]): dfsUtil(x, node, visited, road_used, u, it + 1) # Backtrack through the last # visited nodes for y in road_used: if (y[1] == u): dfsUtil(y[0], node, visited, road_used, u, it + 1) # Function to call the DFS function# which prints the DFS-traversal stepwisedef dfs(node): # Create a array of visited node visited = [False for i in range(node)] # Vector to track last visited road road_used = [] # Initialize all the node with false for i in range(node): visited[i] = False # Call the function dfsUtil(0, node, visited, road_used, -1, 0) # Function to insert edges in Graphdef insertEdge(u, v): adj[u].append(v) adj[v].append(u) # Driver Codeif __name__ == '__main__': # Number of nodes and edges in the graph node = 11 edge = 13 # Function call to create the graph insertEdge(0, 1) insertEdge(0, 2) insertEdge(1, 5) insertEdge(1, 6) insertEdge(2, 4) insertEdge(2, 9) insertEdge(6, 7) insertEdge(6, 8) insertEdge(7, 8) insertEdge(2, 3) insertEdge(3, 9) insertEdge(3, 10) insertEdge(9, 10) # Call the function to print dfs(node) # This code is contributed by mohit kumar 29 // C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static int N = 1000; static List<List<int> > adj = new List<List<int> >(); // Function to print the complete DFS-traversal static void dfsUtil(int u, int node, bool[] visited, List<List<int> > road_used, int parent, int it) { int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.Add(new List<int>() { parent, u }); // Print the node Console.Write(u + " "); // Check for not visited node and proceed with it. foreach(int x in adj[u]) { // call the DFs function if not visited if (!visited[x]) { dfsUtil(x, node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for (int y = 0; y < road_used.Count; y++) { if (road_used[y][1] == u) { dfsUtil(road_used[y][0], node, visited, road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise static void dfs(int node) { // Create a array of visited node bool[] visited = new bool[node]; // Vector to track last visited road List<List<int> > road_used = new List<List<int> >(); // Initialize all the node with false for (int i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph static void insertEdge(int u, int v) { adj[u].Add(v); adj[v].Add(u); } static public void Main() { // number of nodes and edges in the graph int node = 11; for (int i = 0; i < N; i++) { adj.Add(new List<int>()); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); }}// This code is contributed by rag2127 <script>// Javascript program to print the complete// DFS-traversal of graph// using back-tracking let N = 1000; let adj =[]; // Function to print the complete DFS-traversal function dfsUtil(u,node,visited,road_used,parent,it) { let c = 0; // Check if all th node is visited or not // and count unvisited nodes for (let i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.push([ parent, u ]); // Print the node document.write(u + " "); // Check for not visited node and proceed with it. for (let x=0;x<adj[u].length;x++) { // call the DFs function if not visited if (!visited[adj[u][x]]) { dfsUtil(adj[u][x], node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for(let y = 0; y < road_used.length; y++) { if(road_used[y][1] == u) { dfsUtil(road_used[y][0], node, visited,road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise function dfs(node) { // Create a array of visited node let visited = new Array(node); // Vector to track last visited road let road_used = []; // Initialize all the node with false for (let i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph function insertEdge(u,v) { adj[u].push(v); adj[v].push(u); } // Driver Code let node = 11, edge = 13; for(let i = 0; i < N; i++) { adj.push([]); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); // This code is contributed by unknown2108</script>9 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10 mohit kumar 29 avanitrachhadiya2155 rag2127 unknown2108 khushboogoyal499 surinderdawra388 gulshankumarar231 cpp-vector DFS Advanced Data Structure Backtracking Graph DFS Graph Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Quad Tree N Queen Problem | Backtracking-3 Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Backtracking | Introduction Rat in a Maze | Backtracking-2
[ { "code": null, "e": 25733, "s": 25705, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25852, "s": 25733, "text": "Given a graph, the task is to print the DFS traversal of a graph which includes every step including the backtracking." }, { "code": null, "e": 26068, "s": 25852, "text": "1st step:- 0 -> 1\n2nd step:- 1 -> 5\n3rd step:- 5 -> 1 (backtracking step)\n4th step:- 1 -> 6...\nand so on till all the nodes are visited.\n \nDfs step-wise(including backtracking) is:\n0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10" }, { "code": null, "e": 26191, "s": 26068, "text": "Note: In this above diagram the weight between the edges has just been added. It does not have any role in DFS-traversal. " }, { "code": null, "e": 26633, "s": 26191, "text": "Approach: DFS with Backtracking will be used here. First, visit every node using DFS simultaneously and keep track of the previously used edge and the parent node. If a node comes where all the adjacent nodes have been visited, backtrack using the last used edge and print the nodes. Continue the steps and at every step, the parent node will become the present node. Continue the above steps to find the complete DFS traversal of the graph." }, { "code": null, "e": 26684, "s": 26633, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26688, "s": 26684, "text": "C++" }, { "code": null, "e": 26693, "s": 26688, "text": "Java" }, { "code": null, "e": 26701, "s": 26693, "text": "Python3" }, { "code": null, "e": 26704, "s": 26701, "text": "C#" }, { "code": null, "e": 26715, "s": 26704, "text": "Javascript" }, { "code": "// C++ program to print the complete// DFS-traversal of graph// using back-tracking#include <bits/stdc++.h>using namespace std;const int N = 1000;vector<int> adj[N]; // Function to print the complete DFS-traversalvoid dfsUtil(int u, int node, bool visited[], vector<pair<int, int> > road_used, int parent, int it){ int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.push_back({ parent, u }); // Print the node cout << u << \" \"; // Check for not visited node and proceed with it. for (int x : adj[u]) { // call the DFs function if not visited if (!visited[x]) dfsUtil(x, node, visited, road_used, u, it + 1); } // Backtrack through the last // visited nodes for (auto y : road_used) if (y.second == u) dfsUtil(y.first, node, visited, road_used, u, it + 1);} // Function to call the DFS function// which prints the DFS-traversal stepwisevoid dfs(int node){ // Create a array of visited node bool visited[node]; // Vector to track last visited road vector<pair<int, int> > road_used; // Initialize all the node with false for (int i = 0; i < node; i++) visited[i] = false; // call the function dfsUtil(0, node, visited, road_used, -1, 0);} // Function to insert edges in Graphvoid insertEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Driver Codeint main(){ // number of nodes and edges in the graph int node = 11, edge = 13; // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); return 0;}", "e": 28890, "s": 26715, "text": null }, { "code": "// Java program to print the complete// DFS-traversal of graph// using back-trackingimport java.io.*;import java.util.*;class GFG{ static int N = 1000; static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(); // Function to print the complete DFS-traversal static void dfsUtil(int u, int node, boolean visited[], ArrayList<ArrayList<Integer>> road_used, int parent, int it) { int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.add(new ArrayList<Integer>(Arrays.asList( parent, u ))); // Print the node System.out.print(u + \" \"); // Check for not visited node and proceed with it. for (int x : adj.get(u)) { // call the DFs function if not visited if (!visited[x]) { dfsUtil(x, node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for(int y = 0; y < road_used.size(); y++) { if(road_used.get(y).get(1) == u) { dfsUtil(road_used.get(y).get(0), node, visited,road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise static void dfs(int node) { // Create a array of visited node boolean[] visited = new boolean[node]; // Vector to track last visited road ArrayList<ArrayList<Integer>> road_used = new ArrayList<ArrayList<Integer>>(); // Initialize all the node with false for (int i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph static void insertEdge(int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } // Driver Code public static void main (String[] args) { // number of nodes and edges in the graph int node = 11, edge = 13; for(int i = 0; i < N; i++) { adj.add(new ArrayList<Integer>()); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); }} // This code is contributed by avanitrachhadiya2155", "e": 32036, "s": 28890, "text": null }, { "code": "# Python3 program to print the# complete DFS-traversal of graph# using back-trackingN = 1000adj = [[] for i in range(N)] # Function to print the complete DFS-traversaldef dfsUtil(u, node,visited, road_used, parent, it): c = 0 # Check if all th node is visited # or not and count unvisited nodes for i in range(node): if (visited[i]): c += 1 # If all the node is visited return if (c == node): return # Mark not visited node as visited visited[u] = True # Track the current edge road_used.append([parent, u]) # Print the node print(u, end = \" \") # Check for not visited node # and proceed with it. for x in adj[u]: # Call the DFs function # if not visited if (not visited[x]): dfsUtil(x, node, visited, road_used, u, it + 1) # Backtrack through the last # visited nodes for y in road_used: if (y[1] == u): dfsUtil(y[0], node, visited, road_used, u, it + 1) # Function to call the DFS function# which prints the DFS-traversal stepwisedef dfs(node): # Create a array of visited node visited = [False for i in range(node)] # Vector to track last visited road road_used = [] # Initialize all the node with false for i in range(node): visited[i] = False # Call the function dfsUtil(0, node, visited, road_used, -1, 0) # Function to insert edges in Graphdef insertEdge(u, v): adj[u].append(v) adj[v].append(u) # Driver Codeif __name__ == '__main__': # Number of nodes and edges in the graph node = 11 edge = 13 # Function call to create the graph insertEdge(0, 1) insertEdge(0, 2) insertEdge(1, 5) insertEdge(1, 6) insertEdge(2, 4) insertEdge(2, 9) insertEdge(6, 7) insertEdge(6, 8) insertEdge(7, 8) insertEdge(2, 3) insertEdge(3, 9) insertEdge(3, 10) insertEdge(9, 10) # Call the function to print dfs(node) # This code is contributed by mohit kumar 29", "e": 34102, "s": 32036, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { static int N = 1000; static List<List<int> > adj = new List<List<int> >(); // Function to print the complete DFS-traversal static void dfsUtil(int u, int node, bool[] visited, List<List<int> > road_used, int parent, int it) { int c = 0; // Check if all th node is visited or not // and count unvisited nodes for (int i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.Add(new List<int>() { parent, u }); // Print the node Console.Write(u + \" \"); // Check for not visited node and proceed with it. foreach(int x in adj[u]) { // call the DFs function if not visited if (!visited[x]) { dfsUtil(x, node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for (int y = 0; y < road_used.Count; y++) { if (road_used[y][1] == u) { dfsUtil(road_used[y][0], node, visited, road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise static void dfs(int node) { // Create a array of visited node bool[] visited = new bool[node]; // Vector to track last visited road List<List<int> > road_used = new List<List<int> >(); // Initialize all the node with false for (int i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph static void insertEdge(int u, int v) { adj[u].Add(v); adj[v].Add(u); } static public void Main() { // number of nodes and edges in the graph int node = 11; for (int i = 0; i < N; i++) { adj.Add(new List<int>()); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); }}// This code is contributed by rag2127", "e": 36867, "s": 34102, "text": null }, { "code": "<script>// Javascript program to print the complete// DFS-traversal of graph// using back-tracking let N = 1000; let adj =[]; // Function to print the complete DFS-traversal function dfsUtil(u,node,visited,road_used,parent,it) { let c = 0; // Check if all th node is visited or not // and count unvisited nodes for (let i = 0; i < node; i++) if (visited[i]) c++; // If all the node is visited return; if (c == node) return; // Mark not visited node as visited visited[u] = true; // Track the current edge road_used.push([ parent, u ]); // Print the node document.write(u + \" \"); // Check for not visited node and proceed with it. for (let x=0;x<adj[u].length;x++) { // call the DFs function if not visited if (!visited[adj[u][x]]) { dfsUtil(adj[u][x], node, visited, road_used, u, it + 1); } } // Backtrack through the last // visited nodes for(let y = 0; y < road_used.length; y++) { if(road_used[y][1] == u) { dfsUtil(road_used[y][0], node, visited,road_used, u, it + 1); } } } // Function to call the DFS function // which prints the DFS-traversal stepwise function dfs(node) { // Create a array of visited node let visited = new Array(node); // Vector to track last visited road let road_used = []; // Initialize all the node with false for (let i = 0; i < node; i++) { visited[i] = false; } // call the function dfsUtil(0, node, visited, road_used, -1, 0); } // Function to insert edges in Graph function insertEdge(u,v) { adj[u].push(v); adj[v].push(u); } // Driver Code let node = 11, edge = 13; for(let i = 0; i < N; i++) { adj.push([]); } // Function call to create the graph insertEdge(0, 1); insertEdge(0, 2); insertEdge(1, 5); insertEdge(1, 6); insertEdge(2, 4); insertEdge(2, 9); insertEdge(6, 7); insertEdge(6, 8); insertEdge(7, 8); insertEdge(2, 3); insertEdge(3, 9); insertEdge(3, 10); insertEdge(9, 10); // Call the function to print dfs(node); // This code is contributed by unknown2108</script>9", "e": 39514, "s": 36867, "text": null }, { "code": null, "e": 39549, "s": 39514, "text": "0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10" }, { "code": null, "e": 39566, "s": 39551, "text": "mohit kumar 29" }, { "code": null, "e": 39587, "s": 39566, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39595, "s": 39587, "text": "rag2127" }, { "code": null, "e": 39607, "s": 39595, "text": "unknown2108" }, { "code": null, "e": 39624, "s": 39607, "text": "khushboogoyal499" }, { "code": null, "e": 39641, "s": 39624, "text": "surinderdawra388" }, { "code": null, "e": 39659, "s": 39641, "text": "gulshankumarar231" }, { "code": null, "e": 39670, "s": 39659, "text": "cpp-vector" }, { "code": null, "e": 39674, "s": 39670, "text": "DFS" }, { "code": null, "e": 39698, "s": 39674, "text": "Advanced Data Structure" }, { "code": null, "e": 39711, "s": 39698, "text": "Backtracking" }, { "code": null, "e": 39717, "s": 39711, "text": "Graph" }, { "code": null, "e": 39721, "s": 39717, "text": "DFS" }, { "code": null, "e": 39727, "s": 39721, "text": "Graph" }, { "code": null, "e": 39740, "s": 39727, "text": "Backtracking" }, { "code": null, "e": 39838, "s": 39740, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39867, "s": 39838, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 39909, "s": 39867, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 39955, "s": 39909, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 39991, "s": 39955, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 40001, "s": 39991, "text": "Quad Tree" }, { "code": null, "e": 40034, "s": 40001, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 40094, "s": 40034, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40179, "s": 40094, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 40207, "s": 40179, "text": "Backtracking | Introduction" } ]
PostgreSQL - Recursive Query Using CTEs - GeeksforGeeks
11 Aug, 2021 Strictly speaking, this process is iteration, not recursion, but RECURSIVE is the terminology chosen by the SQL standards committee. The general structure of the Postgres recursive query contains, Non-recursive select statementUnion or union allRecursive select statement Non-recursive select statement Union or union all Recursive select statement WITH RECURSIVE name_cte AS ( SELECT statement /* non-recursive statement */ UNION [ALL] SELECT statement /*recursive statement referencing the above select statement */ ) SELECT * FROM name_cte; How does a Postres recursive query work: Evaluate non-recursive statements and creates a temporary tableEvaluate recursive terms and add them to the temporary tableRepeat step 2 till the working table is empty. Evaluate non-recursive statements and creates a temporary table Evaluate recursive terms and add them to the temporary table Repeat step 2 till the working table is empty. The difference between union and union all is that union all allows duplicates union will not allow any duplicates. Example: WITH RECURSIVE tens AS ( SELECT 1 as n UNION ALL SELECT n+1 FROM tens ) SELECT n FROM tens limit 10; This is the basic example of Postres recursive query which prints the first 10 natural numbers. Postres recursive query to find factorial of a natural number: WITH RECURSIVE fact (n, factorial) AS ( SELECT 1 as n, 5 as factorial union all SELECT n+1, factorial*n FROM fact where n < 5 ) SELECT * FROM fact; This query outputs two tables one with the first five natural numbers and the other table with calculations that are performed to find the factorial. We can print only the last row but here we can see how the iteration and calculation take place. Postres recursive query to print Fibonacci series: WITH RECURSIVE fibb AS ( SELECT 1::bigint as n, 0::bigint as a, 1::bigint as b UNION ALL SELECT n+1, b as a, (a+b) as b FROM fibb ) SELECT b FROM fibb limit 10; This prints the Fibonacci series up to 10. With the help of Postgres recursive query, we can find the organizational hierarchy:. To create a table: INSERT INTO employees ( employee_id, full_name, manager_id ) VALUES (1, 'Abhi', NULL), (2, 'Bhargav', 1), (3, 'Chay', 1), (4, 'Dravid', 1), (5, 'Erin', 1), (6, 'Ford', 2), (7, 'Gagan', 2), (8, 'Harry', 3), (9, 'Isaac', 3), (10, 'Jack', 4), (11, 'Kiran', 5); Abhi is the boss, he will be on the first level. Bhargav, Chay, Dravid, Erin are in the next level and the rest of them will be the last level. WITH RECURSIVE subordinates AS ( SELECT employee_id, manager_id, full_name, 0 as level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id, e.full_name, level+1 FROM employees e INNER JOIN subordinates s ON s.employee_id = e.manager_id ) SELECT * FROM subordinates; The output will be: Picked postgreSQL postgreSQL-basics PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - CREATE PROCEDURE PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - TIME Data Type PostgreSQL - REPLACE Function PostgreSQL - CREATE SCHEMA PostgreSQL - SELECT PostgreSQL - ROW_NUMBER Function PostgreSQL - Cursor PostgreSQL - LEFT JOIN
[ { "code": null, "e": 25367, "s": 25339, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25500, "s": 25367, "text": "Strictly speaking, this process is iteration, not recursion, but RECURSIVE is the terminology chosen by the SQL standards committee." }, { "code": null, "e": 25565, "s": 25500, "text": "The general structure of the Postgres recursive query contains," }, { "code": null, "e": 25640, "s": 25565, "text": "Non-recursive select statementUnion or union allRecursive select statement" }, { "code": null, "e": 25671, "s": 25640, "text": "Non-recursive select statement" }, { "code": null, "e": 25690, "s": 25671, "text": "Union or union all" }, { "code": null, "e": 25717, "s": 25690, "text": "Recursive select statement" }, { "code": null, "e": 25914, "s": 25717, "text": "WITH RECURSIVE name_cte AS (\nSELECT statement /* non-recursive statement */\nUNION [ALL]\nSELECT statement /*recursive statement referencing the above select statement */\n)\nSELECT * FROM name_cte;" }, { "code": null, "e": 25955, "s": 25914, "text": "How does a Postres recursive query work:" }, { "code": null, "e": 26125, "s": 25955, "text": "Evaluate non-recursive statements and creates a temporary tableEvaluate recursive terms and add them to the temporary tableRepeat step 2 till the working table is empty." }, { "code": null, "e": 26189, "s": 26125, "text": "Evaluate non-recursive statements and creates a temporary table" }, { "code": null, "e": 26250, "s": 26189, "text": "Evaluate recursive terms and add them to the temporary table" }, { "code": null, "e": 26297, "s": 26250, "text": "Repeat step 2 till the working table is empty." }, { "code": null, "e": 26413, "s": 26297, "text": "The difference between union and union all is that union all allows duplicates union will not allow any duplicates." }, { "code": null, "e": 26422, "s": 26413, "text": "Example:" }, { "code": null, "e": 26530, "s": 26422, "text": "WITH RECURSIVE tens AS (\n SELECT 1 as n\n UNION ALL\n SELECT n+1 FROM tens\n)\nSELECT n FROM tens limit 10;" }, { "code": null, "e": 26626, "s": 26530, "text": "This is the basic example of Postres recursive query which prints the first 10 natural numbers." }, { "code": null, "e": 26689, "s": 26626, "text": "Postres recursive query to find factorial of a natural number:" }, { "code": null, "e": 26845, "s": 26689, "text": "WITH RECURSIVE fact (n, factorial)\nAS (\n SELECT 1 as n, 5 as factorial\nunion all\n SELECT n+1, factorial*n FROM fact where n < 5\n)\nSELECT * FROM fact;" }, { "code": null, "e": 26995, "s": 26845, "text": "This query outputs two tables one with the first five natural numbers and the other table with calculations that are performed to find the factorial." }, { "code": null, "e": 27092, "s": 26995, "text": "We can print only the last row but here we can see how the iteration and calculation take place." }, { "code": null, "e": 27144, "s": 27092, "text": " Postres recursive query to print Fibonacci series:" }, { "code": null, "e": 27313, "s": 27144, "text": "WITH RECURSIVE fibb\nAS (\n SELECT 1::bigint as n, 0::bigint as a, 1::bigint as b\nUNION ALL\n SELECT n+1, b as a, (a+b) as b FROM fibb\n)\nSELECT b FROM fibb limit 10;" }, { "code": null, "e": 27356, "s": 27313, "text": "This prints the Fibonacci series up to 10." }, { "code": null, "e": 27442, "s": 27356, "text": "With the help of Postgres recursive query, we can find the organizational hierarchy:." }, { "code": null, "e": 27461, "s": 27442, "text": "To create a table:" }, { "code": null, "e": 27719, "s": 27461, "text": "INSERT INTO employees (\nemployee_id,\nfull_name,\nmanager_id\n)\nVALUES\n(1, 'Abhi', NULL),\n(2, 'Bhargav', 1),\n(3, 'Chay', 1),\n(4, 'Dravid', 1),\n(5, 'Erin', 1),\n(6, 'Ford', 2),\n(7, 'Gagan', 2),\n(8, 'Harry', 3),\n(9, 'Isaac', 3),\n(10, 'Jack', 4),\n(11, 'Kiran', 5);" }, { "code": null, "e": 27863, "s": 27719, "text": "Abhi is the boss, he will be on the first level. Bhargav, Chay, Dravid, Erin are in the next level and the rest of them will be the last level." }, { "code": null, "e": 28164, "s": 27863, "text": "WITH RECURSIVE subordinates AS (\nSELECT employee_id, manager_id, full_name, 0 as level\nFROM employees\nWHERE manager_id IS NULL\nUNION ALL\nSELECT e.employee_id, e.manager_id, e.full_name, level+1\nFROM employees e\nINNER JOIN subordinates s ON s.employee_id = e.manager_id\n) \nSELECT * FROM subordinates;" }, { "code": null, "e": 28184, "s": 28164, "text": "The output will be:" }, { "code": null, "e": 28191, "s": 28184, "text": "Picked" }, { "code": null, "e": 28202, "s": 28191, "text": "postgreSQL" }, { "code": null, "e": 28220, "s": 28202, "text": "postgreSQL-basics" }, { "code": null, "e": 28231, "s": 28220, "text": "PostgreSQL" }, { "code": null, "e": 28329, "s": 28231, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28359, "s": 28329, "text": "PostgreSQL - CREATE PROCEDURE" }, { "code": null, "e": 28388, "s": 28359, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 28412, "s": 28388, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 28440, "s": 28412, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 28470, "s": 28440, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 28497, "s": 28470, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 28517, "s": 28497, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 28550, "s": 28517, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 28570, "s": 28550, "text": "PostgreSQL - Cursor" } ]
Higher-Order Function in Golang - GeeksforGeeks
16 Jun, 2021 In Go, language, a function is called a Higher-Order Function if it fulfills one of the following conditions:1. Passing Functions as an Argument to Another Function:If a function is passed as an argument to another function, then such types of functions are known as a Higher-Order function. This passing function as an argument is also known as a callback function or first-class function in the Go language. As shown in the below example, here Sphere() function takes a function as an argument and returns vol float64 as an argument. In the Main function, we create an anonymous function whose signature matches the parameter of Sphere function so, we simply call the Sphere() function and pass the result as an argument in it.Example: CSharp // Golang program to illustrate how to pass// a function as an argument to another// functionpackage main import ( "fmt" "math") // Volume function takes// a function as a argumentfunc Sphere(vol func(radius float64) float64) { fmt.Println("Volume of Sphere is:", vol(3))} // Main Functionfunc main() { volume_of_sphere := func(radius float64) float64 { result := 4 / 3 * math.Pi * radius * radius * radius return result } // Passing function as an // argument in Volume function Sphere(volume_of_sphere)} Output: Volume of Sphere is: 84.82300164692441 2. Returning Functions From Another Functions:If a function returns another function, then such types of functions are known as a Higher-Order function. It is also known as the First-Class function. As shown in the below example, here Sphere() function returns an anonymous function that takes one float64 argument and returns a float64 argument. Now in the Main function, sVol stores the function return by Sphere() function, so we call sVol and pass one argument in it.Example: CSharp // Golang program to illustrate how to pass// a function returns another functionpackage main import ( "fmt" "math") // Here, Volume function returns// an anonymous functionfunc Sphere() func(radius float64) float64 { result := func(radius float64) float64 { volume := 4 / 3 * math.Pi * radius * radius * radius return volume } return result } // Main Functionfunc main() { sVol := Sphere() fmt.Println("Volume of Sphere is:", sVol(5))} Output: Volume of Sphere is: 392.69908169872417 sagar0719kumar 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 strings.Replace() Function in Golang With Examples How to Split a String in Golang? Golang Maps Slices in Golang Inheritance in GoLang Different Ways to Find the Type of Variable in Golang Interfaces in Golang How to Trim a String in Golang?
[ { "code": null, "e": 25499, "s": 25471, "text": "\n16 Jun, 2021" }, { "code": null, "e": 26238, "s": 25499, "text": "In Go, language, a function is called a Higher-Order Function if it fulfills one of the following conditions:1. Passing Functions as an Argument to Another Function:If a function is passed as an argument to another function, then such types of functions are known as a Higher-Order function. This passing function as an argument is also known as a callback function or first-class function in the Go language. As shown in the below example, here Sphere() function takes a function as an argument and returns vol float64 as an argument. In the Main function, we create an anonymous function whose signature matches the parameter of Sphere function so, we simply call the Sphere() function and pass the result as an argument in it.Example: " }, { "code": null, "e": 26245, "s": 26238, "text": "CSharp" }, { "code": "// Golang program to illustrate how to pass// a function as an argument to another// functionpackage main import ( \"fmt\" \"math\") // Volume function takes// a function as a argumentfunc Sphere(vol func(radius float64) float64) { fmt.Println(\"Volume of Sphere is:\", vol(3))} // Main Functionfunc main() { volume_of_sphere := func(radius float64) float64 { result := 4 / 3 * math.Pi * radius * radius * radius return result } // Passing function as an // argument in Volume function Sphere(volume_of_sphere)}", "e": 26792, "s": 26245, "text": null }, { "code": null, "e": 26801, "s": 26792, "text": "Output: " }, { "code": null, "e": 26840, "s": 26801, "text": "Volume of Sphere is: 84.82300164692441" }, { "code": null, "e": 27321, "s": 26840, "text": "2. Returning Functions From Another Functions:If a function returns another function, then such types of functions are known as a Higher-Order function. It is also known as the First-Class function. As shown in the below example, here Sphere() function returns an anonymous function that takes one float64 argument and returns a float64 argument. Now in the Main function, sVol stores the function return by Sphere() function, so we call sVol and pass one argument in it.Example: " }, { "code": null, "e": 27328, "s": 27321, "text": "CSharp" }, { "code": "// Golang program to illustrate how to pass// a function returns another functionpackage main import ( \"fmt\" \"math\") // Here, Volume function returns// an anonymous functionfunc Sphere() func(radius float64) float64 { result := func(radius float64) float64 { volume := 4 / 3 * math.Pi * radius * radius * radius return volume } return result } // Main Functionfunc main() { sVol := Sphere() fmt.Println(\"Volume of Sphere is:\", sVol(5))}", "e": 27803, "s": 27328, "text": null }, { "code": null, "e": 27813, "s": 27803, "text": "Output: " }, { "code": null, "e": 27853, "s": 27813, "text": "Volume of Sphere is: 392.69908169872417" }, { "code": null, "e": 27870, "s": 27855, "text": "sagar0719kumar" }, { "code": null, "e": 27882, "s": 27870, "text": "Go Language" }, { "code": null, "e": 27980, "s": 27882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28026, "s": 27980, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28039, "s": 28026, "text": "Arrays in Go" }, { "code": null, "e": 28090, "s": 28039, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28123, "s": 28090, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28135, "s": 28123, "text": "Golang Maps" }, { "code": null, "e": 28152, "s": 28135, "text": "Slices in Golang" }, { "code": null, "e": 28174, "s": 28152, "text": "Inheritance in GoLang" }, { "code": null, "e": 28228, "s": 28174, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 28249, "s": 28228, "text": "Interfaces in Golang" } ]
Hamming Code in Computer Network - GeeksforGeeks
04 May, 2020 Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is technique developed by R.W. Hamming for error correction. Redundant bits – Redundant bits are extra binary bits that are generated and added to the information-carrying bits of data transfer to ensure that no bits were lost during the data transfer.The number of redundant bits can be calculated using the following formula: 2^r ≥ m + r + 1 where, r = redundant bit, m = data bit Suppose the number of data bits is 7, then the number of redundant bits can be calculated using:= 2^4 ≥ 7 + 4 + 1Thus, the number of redundant bits= 4 Parity bits –A parity bit is a bit appended to a data of binary bits to ensure that the total number of 1’s in the data is even or odd. Parity bits are used for error detection. There are two types of parity bits: Even parity bit:In the case of even parity, for a given set of bits, the number of 1’s are counted. If that count is odd, the parity bit value is set to 1, making the total count of occurrences of 1’s an even number. If the total number of 1’s in a given set of bits is already even, the parity bit’s value is 0.Odd Parity bit –In the case of odd parity, for a given set of bits, the number of 1’s are counted. If that count is even, the parity bit value is set to 1, making the total count of occurrences of 1’s an odd number. If the total number of 1’s in a given set of bits is already odd, the parity bit’s value is 0. Even parity bit:In the case of even parity, for a given set of bits, the number of 1’s are counted. If that count is odd, the parity bit value is set to 1, making the total count of occurrences of 1’s an even number. If the total number of 1’s in a given set of bits is already even, the parity bit’s value is 0. Odd Parity bit –In the case of odd parity, for a given set of bits, the number of 1’s are counted. If that count is even, the parity bit value is set to 1, making the total count of occurrences of 1’s an odd number. If the total number of 1’s in a given set of bits is already odd, the parity bit’s value is 0. General Algorithm of Hamming code –The Hamming Code is simply the use of extra parity bits to allow the identification of an error. Write the bit positions starting from 1 in binary form (1, 10, 11, 100, etc).All the bit positions that are a power of 2 are marked as parity bits (1, 2, 4, 8, etc).All the other bit positions are marked as data bits.Each data bit is included in a unique set of parity bits, as determined its bit position in binary form.a. Parity bit 1 covers all the bits positions whose binary representation includes a 1 in the least significantposition (1, 3, 5, 7, 9, 11, etc).b. Parity bit 2 covers all the bits positions whose binary representation includes a 1 in the second position fromthe least significant bit (2, 3, 6, 7, 10, 11, etc).c. Parity bit 4 covers all the bits positions whose binary representation includes a 1 in the third position fromthe least significant bit (4–7, 12–15, 20–23, etc).d. Parity bit 8 covers all the bits positions whose binary representation includes a 1 in the fourth position fromthe least significant bit bits (8–15, 24–31, 40–47, etc).e. In general, each parity bit covers all bits where the bitwise AND of the parity position and the bit position isnon-zero.Since we check for even parity set a parity bit to 1 if the total number of ones in the positions it checks isodd.Set a parity bit to 0 if the total number of ones in the positions it checks is even. Write the bit positions starting from 1 in binary form (1, 10, 11, 100, etc). All the bit positions that are a power of 2 are marked as parity bits (1, 2, 4, 8, etc). All the other bit positions are marked as data bits. Each data bit is included in a unique set of parity bits, as determined its bit position in binary form.a. Parity bit 1 covers all the bits positions whose binary representation includes a 1 in the least significantposition (1, 3, 5, 7, 9, 11, etc).b. Parity bit 2 covers all the bits positions whose binary representation includes a 1 in the second position fromthe least significant bit (2, 3, 6, 7, 10, 11, etc).c. Parity bit 4 covers all the bits positions whose binary representation includes a 1 in the third position fromthe least significant bit (4–7, 12–15, 20–23, etc).d. Parity bit 8 covers all the bits positions whose binary representation includes a 1 in the fourth position fromthe least significant bit bits (8–15, 24–31, 40–47, etc).e. In general, each parity bit covers all bits where the bitwise AND of the parity position and the bit position isnon-zero. Since we check for even parity set a parity bit to 1 if the total number of ones in the positions it checks isodd. Set a parity bit to 0 if the total number of ones in the positions it checks is even. Determining the position of redundant bits –These redundancy bits are placed at the positions which correspond to the power of 2.As in the above example: The number of data bits = 7The number of redundant bits = 4The total number of bits = 11The redundant bits are placed at positions corresponding to power of 2- 1, 2, 4, and 8 The number of data bits = 7 The number of redundant bits = 4 The total number of bits = 11 The redundant bits are placed at positions corresponding to power of 2- 1, 2, 4, and 8 Suppose the data to be transmitted is 1011001, the bits will be placed as follows: Determining the Parity bits – R1 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the least significant position.R1: bits 1, 3, 5, 7, 9, 11To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0R2 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the second position from the least significant bit.R2: bits 2,3,6,7,10,11To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1R4 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the third position from the least significant bit.R4: bits 4, 5, 6, 7To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1R8 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the fourth position from the least significant bit.R8: bit 8,9,10,11To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0.Thus, the data transferred is: R1 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the least significant position.R1: bits 1, 3, 5, 7, 9, 11To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0 R1: bits 1, 3, 5, 7, 9, 11 To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0 R2 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the second position from the least significant bit.R2: bits 2,3,6,7,10,11To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1 R2: bits 2,3,6,7,10,11 To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1 R4 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the third position from the least significant bit.R4: bits 4, 5, 6, 7To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1 R4: bits 4, 5, 6, 7 To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1 R8 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the fourth position from the least significant bit.R8: bit 8,9,10,11To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0.Thus, the data transferred is: R8: bit 8,9,10,11 To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0. Thus, the data transferred is: Error detection and correction –Suppose in the above example the 6th bit is changed from 0 to 1 during data transmission, then it gives new parity values in the binary number: ‘ The bits give the binary number as 0110 whose decimal representation is 6. Thus, the bit 6 contains an error. To correct the error the 6th bit is changed from 1 to 0. shivam_garg Koushik222 PratikRoy Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Socket Programming in Java ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Cache Memory in Computer Organization
[ { "code": null, "e": 37839, "s": 37811, "text": "\n04 May, 2020" }, { "code": null, "e": 38082, "s": 37839, "text": "Hamming code is a set of error-correction codes that can be used to detect and correct the errors that can occur when the data is moved or stored from the sender to the receiver. It is technique developed by R.W. Hamming for error correction." }, { "code": null, "e": 38099, "s": 38082, "text": "Redundant bits –" }, { "code": null, "e": 38349, "s": 38099, "text": "Redundant bits are extra binary bits that are generated and added to the information-carrying bits of data transfer to ensure that no bits were lost during the data transfer.The number of redundant bits can be calculated using the following formula:" }, { "code": null, "e": 38408, "s": 38349, "text": " 2^r ≥ m + r + 1 \n where, r = redundant bit, m = data bit\n" }, { "code": null, "e": 38559, "s": 38408, "text": "Suppose the number of data bits is 7, then the number of redundant bits can be calculated using:= 2^4 ≥ 7 + 4 + 1Thus, the number of redundant bits= 4" }, { "code": null, "e": 38773, "s": 38559, "text": "Parity bits –A parity bit is a bit appended to a data of binary bits to ensure that the total number of 1’s in the data is even or odd. Parity bits are used for error detection. There are two types of parity bits:" }, { "code": null, "e": 39396, "s": 38773, "text": "Even parity bit:In the case of even parity, for a given set of bits, the number of 1’s are counted. If that count is odd, the parity bit value is set to 1, making the total count of occurrences of 1’s an even number. If the total number of 1’s in a given set of bits is already even, the parity bit’s value is 0.Odd Parity bit –In the case of odd parity, for a given set of bits, the number of 1’s are counted. If that count is even, the parity bit value is set to 1, making the total count of occurrences of 1’s an odd number. If the total number of 1’s in a given set of bits is already odd, the parity bit’s value is 0." }, { "code": null, "e": 39709, "s": 39396, "text": "Even parity bit:In the case of even parity, for a given set of bits, the number of 1’s are counted. If that count is odd, the parity bit value is set to 1, making the total count of occurrences of 1’s an even number. If the total number of 1’s in a given set of bits is already even, the parity bit’s value is 0." }, { "code": null, "e": 40020, "s": 39709, "text": "Odd Parity bit –In the case of odd parity, for a given set of bits, the number of 1’s are counted. If that count is even, the parity bit value is set to 1, making the total count of occurrences of 1’s an odd number. If the total number of 1’s in a given set of bits is already odd, the parity bit’s value is 0." }, { "code": null, "e": 40152, "s": 40020, "text": "General Algorithm of Hamming code –The Hamming Code is simply the use of extra parity bits to allow the identification of an error." }, { "code": null, "e": 41443, "s": 40152, "text": "Write the bit positions starting from 1 in binary form (1, 10, 11, 100, etc).All the bit positions that are a power of 2 are marked as parity bits (1, 2, 4, 8, etc).All the other bit positions are marked as data bits.Each data bit is included in a unique set of parity bits, as determined its bit position in binary form.a. Parity bit 1 covers all the bits positions whose binary representation includes a 1 in the least significantposition (1, 3, 5, 7, 9, 11, etc).b. Parity bit 2 covers all the bits positions whose binary representation includes a 1 in the second position fromthe least significant bit (2, 3, 6, 7, 10, 11, etc).c. Parity bit 4 covers all the bits positions whose binary representation includes a 1 in the third position fromthe least significant bit (4–7, 12–15, 20–23, etc).d. Parity bit 8 covers all the bits positions whose binary representation includes a 1 in the fourth position fromthe least significant bit bits (8–15, 24–31, 40–47, etc).e. In general, each parity bit covers all bits where the bitwise AND of the parity position and the bit position isnon-zero.Since we check for even parity set a parity bit to 1 if the total number of ones in the positions it checks isodd.Set a parity bit to 0 if the total number of ones in the positions it checks is even." }, { "code": null, "e": 41521, "s": 41443, "text": "Write the bit positions starting from 1 in binary form (1, 10, 11, 100, etc)." }, { "code": null, "e": 41610, "s": 41521, "text": "All the bit positions that are a power of 2 are marked as parity bits (1, 2, 4, 8, etc)." }, { "code": null, "e": 41663, "s": 41610, "text": "All the other bit positions are marked as data bits." }, { "code": null, "e": 42538, "s": 41663, "text": "Each data bit is included in a unique set of parity bits, as determined its bit position in binary form.a. Parity bit 1 covers all the bits positions whose binary representation includes a 1 in the least significantposition (1, 3, 5, 7, 9, 11, etc).b. Parity bit 2 covers all the bits positions whose binary representation includes a 1 in the second position fromthe least significant bit (2, 3, 6, 7, 10, 11, etc).c. Parity bit 4 covers all the bits positions whose binary representation includes a 1 in the third position fromthe least significant bit (4–7, 12–15, 20–23, etc).d. Parity bit 8 covers all the bits positions whose binary representation includes a 1 in the fourth position fromthe least significant bit bits (8–15, 24–31, 40–47, etc).e. In general, each parity bit covers all bits where the bitwise AND of the parity position and the bit position isnon-zero." }, { "code": null, "e": 42653, "s": 42538, "text": "Since we check for even parity set a parity bit to 1 if the total number of ones in the positions it checks isodd." }, { "code": null, "e": 42739, "s": 42653, "text": "Set a parity bit to 0 if the total number of ones in the positions it checks is even." }, { "code": null, "e": 42893, "s": 42739, "text": "Determining the position of redundant bits –These redundancy bits are placed at the positions which correspond to the power of 2.As in the above example:" }, { "code": null, "e": 43068, "s": 42893, "text": "The number of data bits = 7The number of redundant bits = 4The total number of bits = 11The redundant bits are placed at positions corresponding to power of 2- 1, 2, 4, and 8" }, { "code": null, "e": 43096, "s": 43068, "text": "The number of data bits = 7" }, { "code": null, "e": 43129, "s": 43096, "text": "The number of redundant bits = 4" }, { "code": null, "e": 43159, "s": 43129, "text": "The total number of bits = 11" }, { "code": null, "e": 43246, "s": 43159, "text": "The redundant bits are placed at positions corresponding to power of 2- 1, 2, 4, and 8" }, { "code": null, "e": 43329, "s": 43246, "text": "Suppose the data to be transmitted is 1011001, the bits will be placed as follows:" }, { "code": null, "e": 43359, "s": 43329, "text": "Determining the Parity bits –" }, { "code": null, "e": 44825, "s": 43359, "text": "R1 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the least significant position.R1: bits 1, 3, 5, 7, 9, 11To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0R2 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the second position from the least significant bit.R2: bits 2,3,6,7,10,11To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1R4 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the third position from the least significant bit.R4: bits 4, 5, 6, 7To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1R8 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the fourth position from the least significant bit.R8: bit 8,9,10,11To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0.Thus, the data transferred is:" }, { "code": null, "e": 45182, "s": 44825, "text": "R1 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the least significant position.R1: bits 1, 3, 5, 7, 9, 11To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0" }, { "code": null, "e": 45209, "s": 45182, "text": "R1: bits 1, 3, 5, 7, 9, 11" }, { "code": null, "e": 45399, "s": 45209, "text": "To find the redundant bit R1, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R1 is an even number the value of R1 (parity bit’s value) = 0" }, { "code": null, "e": 45758, "s": 45399, "text": "R2 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the second position from the least significant bit.R2: bits 2,3,6,7,10,11To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1" }, { "code": null, "e": 45781, "s": 45758, "text": "R2: bits 2,3,6,7,10,11" }, { "code": null, "e": 45957, "s": 45781, "text": "To find the redundant bit R2, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R2 is odd the value of R2(parity bit’s value)=1" }, { "code": null, "e": 46314, "s": 45957, "text": "R4 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the third position from the least significant bit.R4: bits 4, 5, 6, 7To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1" }, { "code": null, "e": 46334, "s": 46314, "text": "R4: bits 4, 5, 6, 7" }, { "code": null, "e": 46512, "s": 46334, "text": "To find the redundant bit R4, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R4 is odd the value of R4(parity bit’s value) = 1" }, { "code": null, "e": 46908, "s": 46512, "text": "R8 bit is calculated using parity check at all the bits positions whose binary representation includes a 1 in the fourth position from the least significant bit.R8: bit 8,9,10,11To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0.Thus, the data transferred is:" }, { "code": null, "e": 46926, "s": 46908, "text": "R8: bit 8,9,10,11" }, { "code": null, "e": 47114, "s": 46926, "text": "To find the redundant bit R8, we check for even parity. Since the total number of 1’s in all the bit positions corresponding to R8 is an even number the value of R8(parity bit’s value)=0." }, { "code": null, "e": 47145, "s": 47114, "text": "Thus, the data transferred is:" }, { "code": null, "e": 47321, "s": 47145, "text": "Error detection and correction –Suppose in the above example the 6th bit is changed from 0 to 1 during data transmission, then it gives new parity values in the binary number:" }, { "code": null, "e": 47323, "s": 47321, "text": "‘" }, { "code": null, "e": 47490, "s": 47323, "text": "The bits give the binary number as 0110 whose decimal representation is 6. Thus, the bit 6 contains an error. To correct the error the 6th bit is changed from 1 to 0." }, { "code": null, "e": 47502, "s": 47490, "text": "shivam_garg" }, { "code": null, "e": 47513, "s": 47502, "text": "Koushik222" }, { "code": null, "e": 47523, "s": 47513, "text": "PratikRoy" }, { "code": null, "e": 47541, "s": 47523, "text": "Computer Networks" }, { "code": null, "e": 47549, "s": 47541, "text": "GATE CS" }, { "code": null, "e": 47567, "s": 47549, "text": "Computer Networks" }, { "code": null, "e": 47665, "s": 47567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47699, "s": 47665, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 47728, "s": 47699, "text": "Socket Programming in Python" }, { "code": null, "e": 47758, "s": 47728, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 47796, "s": 47758, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 47823, "s": 47796, "text": "Socket Programming in Java" }, { "code": null, "e": 47847, "s": 47823, "text": "ACID Properties in DBMS" }, { "code": null, "e": 47874, "s": 47847, "text": "Types of Operating Systems" }, { "code": null, "e": 47895, "s": 47874, "text": "Normal Forms in DBMS" }, { "code": null, "e": 47944, "s": 47895, "text": "Page Replacement Algorithms in Operating Systems" } ]
Google Chrome Dino Bot using Image Recognition | Python - GeeksforGeeks
30 Nov, 2021 What would you see in your Chrome browser when there is no internet connection ? Yes, everybody knows that dinosaur game that comes on screen. So, in this article, we are going to build a simple python bot that plays Chrome Dino Game without user interaction. Here we are not using any machine learning or artificial intelligence to counter this problem but we will use simple image/screen processing. We will work with Pyautogui and PIL (Python Imaging Library) for implementation. This project is very basic and consists of only about 50 lines of code but its result will make you surprise. Some libraries used are: PIL : Python Imaging Library (PIL) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. Pyautogui : PyAutoGUI is a Python module for programmatically controlling the mouse and keyboard without any user interaction.Time : Python “Time” Module which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life.Numpy :NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. PIL : Python Imaging Library (PIL) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. Pyautogui : PyAutoGUI is a Python module for programmatically controlling the mouse and keyboard without any user interaction. Time : Python “Time” Module which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. Numpy :NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Algorithm – Click on the restart button using Pyautogui library using “replaybutton” coordinates.Calculate the sum of all white pixels values present in the box in front of Dinosaur.If the sum of pixels values present at any time in the box becomes less than the sum of white pixels values, it means either “bush” or “bird” is coming. So either we have to make our Dino jump or bend down.In order to protect Dino from “Bush”, we make a jump.In order to protect Dino from “Bird”, we always keep our Dino down. Click on the restart button using Pyautogui library using “replaybutton” coordinates. Calculate the sum of all white pixels values present in the box in front of Dinosaur. If the sum of pixels values present at any time in the box becomes less than the sum of white pixels values, it means either “bush” or “bird” is coming. So either we have to make our Dino jump or bend down. In order to protect Dino from “Bush”, we make a jump. In order to protect Dino from “Bird”, we always keep our Dino down. Below is the Python implementation – Python3 # importing above defined libraries to# implement the functionalitiesfrom PIL import ImageGrab, ImageOpsimport pyautoguiimport timeimport numpy as np class coordinates(): # coordinates of replay button to start the game replaybutton =(360, 214) # this coordinates represent the top-right coordinates # that will be used to define the front box dinasaur = (149, 239 ) def restartGame(): # using pyautogui library, we are clicking on the # replay button without any user interaction pyautogui.click(coordinates.replaybutton) # we will keep our Bot always down that # will prevent him to get hit by bird pyautogui.keyDown('down') def press_space(): # releasing the Down Key pyautogui.keyUp('down') # pressing Space to overcome Bush pyautogui.keyDown('space') # so that Space Key will be recognized easily time.sleep(0.05) # printing the "Jump" statement on the # terminal to see the current output print("jump") time.sleep(0.10) # releasing the Space Key pyautogui.keyUp('space') # again pressing the Down Key to keep my Bot always down pyautogui.keyDown('down') def imageGrab(): # defining the coordinates of box in front of dinosaur box = (coordinates.dinasaur[0]+30, coordinates.dinasaur[1], coordinates.dinasaur[0]+120, coordinates.dinasaur[1]+2) # grabbing all the pixels values in form of RGB tuples image = ImageGrab.grab(box) # converting RGB to Grayscale to # make processing easy and result faster grayImage = ImageOps.grayscale(image) # using numpy to get sum of all grayscale pixels a = np.array(grayImage.getcolors()) # returning the sum print(a.sum()) return a.sum() # function to restart the gamerestartGame()while True: # 435 is the sum of white pixels values of box. # You may get different value is you are taking bigger # or smaller box than the box taken in this article. # if value returned by "imageGrab" function is not equal to 435, # it means either bird or bush is coming towards dinosaur if(imageGrab()!= 435): press_space() # time to recognize the operation performed by above function time.sleep(0.1) Output : YouTubeAditya Atri18 subscribersGoogle Dinosaur Bot using pythonWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=QoBAfQGJsKA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Improvements : Over a period of time, the Dino Bot Game becomes fast. The Birds and Bushes start coming very fast. So we are not making our Bot to learn all these things, changing its speed based on past learning. So our bot will function for around 2000 score. In order to score more, we have to apply machine learning and artificial intelligence. sumitgumber28 gabaa406 simmytarika5 Project Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Banking Transaction System using Java Student record management system using linked list E-commerce Website using Django Handling Ajax request in Django How to write a good SRS for your Project Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25723, "s": 25695, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26127, "s": 25723, "text": "What would you see in your Chrome browser when there is no internet connection ? Yes, everybody knows that dinosaur game that comes on screen. So, in this article, we are going to build a simple python bot that plays Chrome Dino Game without user interaction. Here we are not using any machine learning or artificial intelligence to counter this problem but we will use simple image/screen processing. " }, { "code": null, "e": 26344, "s": 26127, "text": "We will work with Pyautogui and PIL (Python Imaging Library) for implementation. This project is very basic and consists of only about 50 lines of code but its result will make you surprise. Some libraries used are: " }, { "code": null, "e": 27051, "s": 26344, "text": "PIL : Python Imaging Library (PIL) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. Pyautogui : PyAutoGUI is a Python module for programmatically controlling the mouse and keyboard without any user interaction.Time : Python “Time” Module which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life.Numpy :NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays." }, { "code": null, "e": 27233, "s": 27051, "text": "PIL : Python Imaging Library (PIL) is a free library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. " }, { "code": null, "e": 27360, "s": 27233, "text": "Pyautogui : PyAutoGUI is a Python module for programmatically controlling the mouse and keyboard without any user interaction." }, { "code": null, "e": 27538, "s": 27360, "text": "Time : Python “Time” Module which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life." }, { "code": null, "e": 27761, "s": 27538, "text": "Numpy :NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays." }, { "code": null, "e": 27774, "s": 27761, "text": "Algorithm – " }, { "code": null, "e": 28271, "s": 27774, "text": "Click on the restart button using Pyautogui library using “replaybutton” coordinates.Calculate the sum of all white pixels values present in the box in front of Dinosaur.If the sum of pixels values present at any time in the box becomes less than the sum of white pixels values, it means either “bush” or “bird” is coming. So either we have to make our Dino jump or bend down.In order to protect Dino from “Bush”, we make a jump.In order to protect Dino from “Bird”, we always keep our Dino down." }, { "code": null, "e": 28357, "s": 28271, "text": "Click on the restart button using Pyautogui library using “replaybutton” coordinates." }, { "code": null, "e": 28443, "s": 28357, "text": "Calculate the sum of all white pixels values present in the box in front of Dinosaur." }, { "code": null, "e": 28650, "s": 28443, "text": "If the sum of pixels values present at any time in the box becomes less than the sum of white pixels values, it means either “bush” or “bird” is coming. So either we have to make our Dino jump or bend down." }, { "code": null, "e": 28704, "s": 28650, "text": "In order to protect Dino from “Bush”, we make a jump." }, { "code": null, "e": 28772, "s": 28704, "text": "In order to protect Dino from “Bird”, we always keep our Dino down." }, { "code": null, "e": 28810, "s": 28772, "text": "Below is the Python implementation – " }, { "code": null, "e": 28818, "s": 28810, "text": "Python3" }, { "code": "# importing above defined libraries to# implement the functionalitiesfrom PIL import ImageGrab, ImageOpsimport pyautoguiimport timeimport numpy as np class coordinates(): # coordinates of replay button to start the game replaybutton =(360, 214) # this coordinates represent the top-right coordinates # that will be used to define the front box dinasaur = (149, 239 ) def restartGame(): # using pyautogui library, we are clicking on the # replay button without any user interaction pyautogui.click(coordinates.replaybutton) # we will keep our Bot always down that # will prevent him to get hit by bird pyautogui.keyDown('down') def press_space(): # releasing the Down Key pyautogui.keyUp('down') # pressing Space to overcome Bush pyautogui.keyDown('space') # so that Space Key will be recognized easily time.sleep(0.05) # printing the \"Jump\" statement on the # terminal to see the current output print(\"jump\") time.sleep(0.10) # releasing the Space Key pyautogui.keyUp('space') # again pressing the Down Key to keep my Bot always down pyautogui.keyDown('down') def imageGrab(): # defining the coordinates of box in front of dinosaur box = (coordinates.dinasaur[0]+30, coordinates.dinasaur[1], coordinates.dinasaur[0]+120, coordinates.dinasaur[1]+2) # grabbing all the pixels values in form of RGB tuples image = ImageGrab.grab(box) # converting RGB to Grayscale to # make processing easy and result faster grayImage = ImageOps.grayscale(image) # using numpy to get sum of all grayscale pixels a = np.array(grayImage.getcolors()) # returning the sum print(a.sum()) return a.sum() # function to restart the gamerestartGame()while True: # 435 is the sum of white pixels values of box. # You may get different value is you are taking bigger # or smaller box than the box taken in this article. # if value returned by \"imageGrab\" function is not equal to 435, # it means either bird or bush is coming towards dinosaur if(imageGrab()!= 435): press_space() # time to recognize the operation performed by above function time.sleep(0.1) ", "e": 31046, "s": 28818, "text": null }, { "code": null, "e": 31056, "s": 31046, "text": "Output : " }, { "code": null, "e": 31867, "s": 31056, "text": "YouTubeAditya Atri18 subscribersGoogle Dinosaur Bot using pythonWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=QoBAfQGJsKA\" 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": 32217, "s": 31867, "text": "Improvements : Over a period of time, the Dino Bot Game becomes fast. The Birds and Bushes start coming very fast. So we are not making our Bot to learn all these things, changing its speed based on past learning. So our bot will function for around 2000 score. In order to score more, we have to apply machine learning and artificial intelligence. " }, { "code": null, "e": 32231, "s": 32217, "text": "sumitgumber28" }, { "code": null, "e": 32240, "s": 32231, "text": "gabaa406" }, { "code": null, "e": 32253, "s": 32240, "text": "simmytarika5" }, { "code": null, "e": 32261, "s": 32253, "text": "Project" }, { "code": null, "e": 32268, "s": 32261, "text": "Python" }, { "code": null, "e": 32284, "s": 32268, "text": "Python Programs" }, { "code": null, "e": 32382, "s": 32284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32420, "s": 32382, "text": "Banking Transaction System using Java" }, { "code": null, "e": 32471, "s": 32420, "text": "Student record management system using linked list" }, { "code": null, "e": 32503, "s": 32471, "text": "E-commerce Website using Django" }, { "code": null, "e": 32535, "s": 32503, "text": "Handling Ajax request in Django" }, { "code": null, "e": 32576, "s": 32535, "text": "How to write a good SRS for your Project" }, { "code": null, "e": 32604, "s": 32576, "text": "Read JSON file using Python" }, { "code": null, "e": 32654, "s": 32604, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 32676, "s": 32654, "text": "Python map() function" } ]
Process Management in Linux - GeeksforGeeks
17 May, 2020 A process means program in execution. It generally takes an input, processes it and gives us the appropriate output. Check Introduction to Process Management for more details about a process. There are basically 2 types of processes. Foreground processes: Such kind of processes are also known as interactive processes. These are the processes which are to be executed or initiated by the user or the programmer, they can not be initialized by system services. Such processes take input from the user and return the output. While these processes are running we can not directly initiate a new process from the same terminal.Background processes: Such kind of processes are also known as non interactive processes. These are the processes that are to be executed or initiated by the system itself or by users, though they can even be managed by users. These processes have a unique PID or process if assigned to them and we can initiate other processes within the same terminal from which they are initiated. Foreground processes: Such kind of processes are also known as interactive processes. These are the processes which are to be executed or initiated by the user or the programmer, they can not be initialized by system services. Such processes take input from the user and return the output. While these processes are running we can not directly initiate a new process from the same terminal. Background processes: Such kind of processes are also known as non interactive processes. These are the processes that are to be executed or initiated by the system itself or by users, though they can even be managed by users. These processes have a unique PID or process if assigned to them and we can initiate other processes within the same terminal from which they are initiated. 1. Example of foreground process. sleep 5 This command will be executed in the terminal and we would be able to execute another command after the execution of the above command. Note: In this case, the name of the process is sleep 5 but you may change the same as per your need. 2. Stopping a process in between of its execution. To stop a foreground process in between of its execution we may press CTRL+Z to force stop it. sleep 100 Pressing CTRL+Z in between the execution of the command will stop it. Note: In this case the name of the process is sleep 100 but you may change the same as per your need. 3. To get the list of jobs that are either running or stopped. jobs It will display the stopped processes in this terminal and even the pending ones. 4. To run all the pending and force stopped jobs in the background. bg This will start the stopped and pending processes in the background. 5. To get details of a process running in background. ps -ef | grep sleep Note: In this case the name of the process is sleep 100 but you may change the same as per your need. 6. To run all the pending and force stopped jobs in the foreground. fg This will start the stopped and pending processes in the foreground. 7. To run a process in the background without getting impacted by the closing of the terminal. nohup sleep 100 & While executing, it will even store all the output after execution in nohup.out file. Note: In this case, the process is sleep 100, you may modify it as per your need. 8. To run some processes in the background directly. sleep 100& This will run the process in the background and will display the process id of the process.Note:- In this case, the process is sleep 100, you may modify it as per your need. 9. To run processes with priority. nice -n 5 sleep 100 The top priority is -20 but as it may affect the system processes so we have used the priority 5. Note: In this case, the process is sleep 100, you may modify it as per your need. 10. To get the list of all the running processes on your Linux machine. top This will display all the processes that are currently running in your system. Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n17 May, 2020" }, { "code": null, "e": 25885, "s": 25651, "text": "A process means program in execution. It generally takes an input, processes it and gives us the appropriate output. Check Introduction to Process Management for more details about a process. There are basically 2 types of processes." }, { "code": null, "e": 26659, "s": 25885, "text": "Foreground processes: Such kind of processes are also known as interactive processes. These are the processes which are to be executed or initiated by the user or the programmer, they can not be initialized by system services. Such processes take input from the user and return the output. While these processes are running we can not directly initiate a new process from the same terminal.Background processes: Such kind of processes are also known as non interactive processes. These are the processes that are to be executed or initiated by the system itself or by users, though they can even be managed by users. These processes have a unique PID or process if assigned to them and we can initiate other processes within the same terminal from which they are initiated." }, { "code": null, "e": 27050, "s": 26659, "text": "Foreground processes: Such kind of processes are also known as interactive processes. These are the processes which are to be executed or initiated by the user or the programmer, they can not be initialized by system services. Such processes take input from the user and return the output. While these processes are running we can not directly initiate a new process from the same terminal." }, { "code": null, "e": 27434, "s": 27050, "text": "Background processes: Such kind of processes are also known as non interactive processes. These are the processes that are to be executed or initiated by the system itself or by users, though they can even be managed by users. These processes have a unique PID or process if assigned to them and we can initiate other processes within the same terminal from which they are initiated." }, { "code": null, "e": 27468, "s": 27434, "text": "1. Example of foreground process." }, { "code": null, "e": 27476, "s": 27468, "text": "sleep 5" }, { "code": null, "e": 27612, "s": 27476, "text": "This command will be executed in the terminal and we would be able to execute another command after the execution of the above command." }, { "code": null, "e": 27713, "s": 27612, "text": "Note: In this case, the name of the process is sleep 5 but you may change the same as per your need." }, { "code": null, "e": 27859, "s": 27713, "text": "2. Stopping a process in between of its execution. To stop a foreground process in between of its execution we may press CTRL+Z to force stop it." }, { "code": null, "e": 27869, "s": 27859, "text": "sleep 100" }, { "code": null, "e": 27939, "s": 27869, "text": "Pressing CTRL+Z in between the execution of the command will stop it." }, { "code": null, "e": 28041, "s": 27939, "text": "Note: In this case the name of the process is sleep 100 but you may change the same as per your need." }, { "code": null, "e": 28104, "s": 28041, "text": "3. To get the list of jobs that are either running or stopped." }, { "code": null, "e": 28109, "s": 28104, "text": "jobs" }, { "code": null, "e": 28191, "s": 28109, "text": "It will display the stopped processes in this terminal and even the pending ones." }, { "code": null, "e": 28259, "s": 28191, "text": "4. To run all the pending and force stopped jobs in the background." }, { "code": null, "e": 28262, "s": 28259, "text": "bg" }, { "code": null, "e": 28331, "s": 28262, "text": "This will start the stopped and pending processes in the background." }, { "code": null, "e": 28385, "s": 28331, "text": "5. To get details of a process running in background." }, { "code": null, "e": 28405, "s": 28385, "text": "ps -ef | grep sleep" }, { "code": null, "e": 28507, "s": 28405, "text": "Note: In this case the name of the process is sleep 100 but you may change the same as per your need." }, { "code": null, "e": 28575, "s": 28507, "text": "6. To run all the pending and force stopped jobs in the foreground." }, { "code": null, "e": 28578, "s": 28575, "text": "fg" }, { "code": null, "e": 28647, "s": 28578, "text": "This will start the stopped and pending processes in the foreground." }, { "code": null, "e": 28742, "s": 28647, "text": "7. To run a process in the background without getting impacted by the closing of the terminal." }, { "code": null, "e": 28760, "s": 28742, "text": "nohup sleep 100 &" }, { "code": null, "e": 28846, "s": 28760, "text": "While executing, it will even store all the output after execution in nohup.out file." }, { "code": null, "e": 28928, "s": 28846, "text": "Note: In this case, the process is sleep 100, you may modify it as per your need." }, { "code": null, "e": 28981, "s": 28928, "text": "8. To run some processes in the background directly." }, { "code": null, "e": 28992, "s": 28981, "text": "sleep 100&" }, { "code": null, "e": 29166, "s": 28992, "text": "This will run the process in the background and will display the process id of the process.Note:- In this case, the process is sleep 100, you may modify it as per your need." }, { "code": null, "e": 29201, "s": 29166, "text": "9. To run processes with priority." }, { "code": null, "e": 29222, "s": 29201, "text": "nice -n 5 sleep 100 " }, { "code": null, "e": 29320, "s": 29222, "text": "The top priority is -20 but as it may affect the system processes so we have used the priority 5." }, { "code": null, "e": 29402, "s": 29320, "text": "Note: In this case, the process is sleep 100, you may modify it as per your need." }, { "code": null, "e": 29474, "s": 29402, "text": "10. To get the list of all the running processes on your Linux machine." }, { "code": null, "e": 29478, "s": 29474, "text": "top" }, { "code": null, "e": 29557, "s": 29478, "text": "This will display all the processes that are currently running in your system." }, { "code": null, "e": 29568, "s": 29557, "text": "Linux-Unix" }, { "code": null, "e": 29666, "s": 29568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29701, "s": 29666, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29727, "s": 29701, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29761, "s": 29727, "text": "mv command in Linux with examples" }, { "code": null, "e": 29790, "s": 29761, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29827, "s": 29790, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29864, "s": 29827, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29906, "s": 29864, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29932, "s": 29906, "text": "Thread functions in C/C++" }, { "code": null, "e": 29968, "s": 29932, "text": "uniq Command in LINUX with examples" } ]
Perl | Modules - GeeksforGeeks
17 Feb, 2019 A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN). These modules cover a wide range of categories such as network, CGI, XML processing, databases interfacing, etc. A modules name must be same as to the name of the Package and should end with .pm extension. Example : Calculator.pm package Calculator; # Defining sub-routine for Multiplicationsub multiplication{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a * $b; # Function to print the Sum print "\n***Multiplication is $a";} # Defining sub-routine for Divisionsub division{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a / $b; # Function to print the answer print "\n***Division is $a";}1; Here, the name of the file is “Calculator.pm” stored in the directory Calculator. Notice that 1; is written at the end of the code to return a true value to the interpreter. Perl accepts anything which is true instead of 1 Examples: Test.pl #!/usr/bin/perl # Using the Package 'Calculator'use Calculator; print "Enter two numbers to multiply"; # Defining values to the variables$a = 5;$b = 10; # Subroutine callCalculator::multiplication($a, $b); print "\nEnter two numbers to divide"; # Defining values to the variables$a = 45;$b = 5; # Subroutine callCalculator::division($a, $b); Output: Variables from different packages can be used by declaring them before using. Following example demonstrates thisExamples: Message.pm #!/usr/bin/perl package Message; # Variable Creation$username; # Defining subroutinesub Hello{ print "Hello $username\n";}1; Perl file to access the module is as belowExamples: variable.pl #!/usr/bin/perl # Using Message.pm packageuse Message; # Defining value to variable$Message::username = "Geeks"; # Subroutine callMessage::Hello(); Output: Example: #!/usr/bin/perl use strict;use warnings; print" Hello This program uses Pre-defined Modules"; Output: Hello This program uses Pre-defined Modules perl-basics Picked 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": "\n17 Feb, 2019" }, { "code": null, "e": 26861, "s": 26525, "text": "A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN). These modules cover a wide range of categories such as network, CGI, XML processing, databases interfacing, etc." }, { "code": null, "e": 26954, "s": 26861, "text": "A modules name must be same as to the name of the Package and should end with .pm extension." }, { "code": null, "e": 26978, "s": 26954, "text": "Example : Calculator.pm" }, { "code": "package Calculator; # Defining sub-routine for Multiplicationsub multiplication{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a * $b; # Function to print the Sum print \"\\n***Multiplication is $a\";} # Defining sub-routine for Divisionsub division{ # Initializing Variables a & b $a = $_[0]; $b = $_[1]; # Performing the operation $a = $a / $b; # Function to print the answer print \"\\n***Division is $a\";}1;", "e": 27495, "s": 26978, "text": null }, { "code": null, "e": 27719, "s": 27495, "text": "Here, the name of the file is “Calculator.pm” stored in the directory Calculator. Notice that 1; is written at the end of the code to return a true value to the interpreter. Perl accepts anything which is true instead of 1 " }, { "code": null, "e": 27737, "s": 27719, "text": "Examples: Test.pl" }, { "code": "#!/usr/bin/perl # Using the Package 'Calculator'use Calculator; print \"Enter two numbers to multiply\"; # Defining values to the variables$a = 5;$b = 10; # Subroutine callCalculator::multiplication($a, $b); print \"\\nEnter two numbers to divide\"; # Defining values to the variables$a = 45;$b = 5; # Subroutine callCalculator::division($a, $b);", "e": 28086, "s": 27737, "text": null }, { "code": null, "e": 28094, "s": 28086, "text": "Output:" }, { "code": null, "e": 28228, "s": 28094, "text": "Variables from different packages can be used by declaring them before using. Following example demonstrates thisExamples: Message.pm" }, { "code": "#!/usr/bin/perl package Message; # Variable Creation$username; # Defining subroutinesub Hello{ print \"Hello $username\\n\";}1;", "e": 28357, "s": 28228, "text": null }, { "code": null, "e": 28421, "s": 28357, "text": "Perl file to access the module is as belowExamples: variable.pl" }, { "code": "#!/usr/bin/perl # Using Message.pm packageuse Message; # Defining value to variable$Message::username = \"Geeks\"; # Subroutine callMessage::Hello();", "e": 28572, "s": 28421, "text": null }, { "code": null, "e": 28580, "s": 28572, "text": "Output:" }, { "code": null, "e": 28589, "s": 28580, "text": "Example:" }, { "code": "#!/usr/bin/perl use strict;use warnings; print\" Hello This program uses Pre-defined Modules\";", "e": 28685, "s": 28589, "text": null }, { "code": null, "e": 28693, "s": 28685, "text": "Output:" }, { "code": null, "e": 28737, "s": 28693, "text": "Hello This program uses Pre-defined Modules" }, { "code": null, "e": 28749, "s": 28737, "text": "perl-basics" }, { "code": null, "e": 28756, "s": 28749, "text": "Picked" }, { "code": null, "e": 28761, "s": 28756, "text": "Perl" }, { "code": null, "e": 28766, "s": 28761, "text": "Perl" }, { "code": null, "e": 28864, "s": 28766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28888, "s": 28864, "text": "Perl | split() Function" }, { "code": null, "e": 28911, "s": 28888, "text": "Perl | push() Function" }, { "code": null, "e": 28935, "s": 28911, "text": "Perl | chomp() Function" }, { "code": null, "e": 28958, "s": 28935, "text": "Perl | grep() Function" }, { "code": null, "e": 28983, "s": 28958, "text": "Perl | substr() function" }, { "code": null, "e": 29008, "s": 28983, "text": "Perl | exists() Function" }, { "code": null, "e": 29049, "s": 29008, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 29106, "s": 29049, "text": "Perl | Removing leading and trailing white spaces (trim)" }, { "code": null, "e": 29139, "s": 29106, "text": "Use of print() and say() in Perl" } ]
Implementation of Logistic Regression from Scratch using Python - GeeksforGeeks
25 Oct, 2020 Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classification problem, where we need to classify whether an email is a spam or not. So, the hypothetical function of linear regression could not be used here to predict as it predicts unbound values, but we have to predict either 0 or 1. To do, so we apply the sigmoid activation function on the hypothetical function of linear regression. So the resultant hypothetical function for logistic regression is given below : h( x ) = sigmoid( wx + b ) Here, w is the weight vector. x is the feature vector. b is the bias. sigmoid( z ) = 1 / ( 1 + e( - z ) ) The cost function of linear regression ( or mean square error ) can’t be used in logistic regression because it is a non-convex function of weights. Optimizing algorithms like i.e gradient descent only converge convex function into a global minimum. So, the simplified cost function we use : J = - ylog( h(x) ) - ( 1 - y )log( 1 - h(x) ) here, y is the real target value h( x ) = sigmoid( wx + b ) For y = 0, J = - log( 1 - h(x) ) and y = 1, J = - log( h(x) ) This cost function is because when we train, we need to maximize the probability by minimizing the loss function. Gradient Descent Calculation: repeat until convergence { tmpi = wi - alpha * dwi wi = tmpi } where alpha is the learning rate. The chain rule is used to calculate the gradients like i.e dw. Chain rule for dw here, a = sigmoid( z ) and z = wx + b. Diabetes Dataset used in this implementation can be downloaded from link. It has 8 features columns like i.e “Age“, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will train a Logistic Regression Classifier model to predict the presence of diabetes or not for patients with such information. # Importing librariesimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitimport warningswarnings.filterwarnings( "ignore" ) # to compare our model's accuracy with sklearn modelfrom sklearn.linear_model import LogisticRegression# Logistic Regressionclass LogitRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : A = 1 / ( 1 + np.exp( - ( self.X.dot( self.W ) + self.b ) ) ) # calculate gradients tmp = ( A - self.Y.T ) tmp = np.reshape( tmp, self.m ) dW = np.dot( self.X.T, tmp ) / self.m db = np.sum( tmp ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : Z = 1 / ( 1 + np.exp( - ( X.dot( self.W ) + self.b ) ) ) Y = np.where( Z > 0.5, 1, 0 ) return Y # Driver code def main() : # Importing dataset df = pd.read_csv( "diabetes.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = LogitRegression( learning_rate = 0.01, iterations = 1000 ) model.fit( X_train, Y_train ) model1 = LogisticRegression() model1.fit( X_train, Y_train) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) # measure performance correctly_classified = 0 correctly_classified1 = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 if Y_test[count] == Y_pred1[count] : correctly_classified1 = correctly_classified1 + 1 count = count + 1 print( "Accuracy on test set by our model : ", ( correctly_classified / count ) * 100 ) print( "Accuracy on test set by sklearn model : ", ( correctly_classified1 / count ) * 100 ) if __name__ == "__main__" : main() Accuracy on test set by our model : 58.333333333333336 Accuracy on test set by sklearn model : 61.111111111111114 Note: The above-trained model is to implement the mathematical intuition not just for improving accuracies. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25589, "s": 25561, "text": "\n25 Oct, 2020" }, { "code": null, "e": 26153, "s": 25589, "text": "Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classification problem, where we need to classify whether an email is a spam or not. So, the hypothetical function of linear regression could not be used here to predict as it predicts unbound values, but we have to predict either 0 or 1." }, { "code": null, "e": 26335, "s": 26153, "text": "To do, so we apply the sigmoid activation function on the hypothetical function of linear regression. So the resultant hypothetical function for logistic regression is given below :" }, { "code": null, "e": 26472, "s": 26335, "text": "h( x ) = sigmoid( wx + b )\n\nHere, w is the weight vector.\nx is the feature vector. \nb is the bias.\n\nsigmoid( z ) = 1 / ( 1 + e( - z ) )\n" }, { "code": null, "e": 26723, "s": 26472, "text": "The cost function of linear regression ( or mean square error ) can’t be used in logistic regression because it is a non-convex function of weights. Optimizing algorithms like i.e gradient descent only converge convex function into a global minimum. " }, { "code": null, "e": 26765, "s": 26723, "text": "So, the simplified cost function we use :" }, { "code": null, "e": 26940, "s": 26765, "text": "J = - ylog( h(x) ) - ( 1 - y )log( 1 - h(x) )\n\nhere, y is the real target value\n\nh( x ) = sigmoid( wx + b )\n\nFor y = 0,\n\nJ = - log( 1 - h(x) )\n\nand y = 1,\n\nJ = - log( h(x) )\n" }, { "code": null, "e": 27055, "s": 26940, "text": "This cost function is because when we train, we need to maximize the probability by minimizing the loss function. " }, { "code": null, "e": 27086, "s": 27055, "text": "Gradient Descent Calculation: " }, { "code": null, "e": 27208, "s": 27086, "text": "repeat until convergence {\n tmpi = wi - alpha * dwi\n wi = tmpi \n}\nwhere alpha is the learning rate.\n" }, { "code": null, "e": 27271, "s": 27208, "text": "The chain rule is used to calculate the gradients like i.e dw." }, { "code": null, "e": 27289, "s": 27271, "text": "Chain rule for dw" }, { "code": null, "e": 27329, "s": 27289, "text": "here, a = sigmoid( z ) and z = wx + b.\n" }, { "code": null, "e": 27403, "s": 27329, "text": "Diabetes Dataset used in this implementation can be downloaded from link." }, { "code": null, "e": 27658, "s": 27403, "text": "It has 8 features columns like i.e “Age“, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will train a Logistic Regression Classifier model to predict the presence of diabetes or not for patients with such information." }, { "code": "# Importing librariesimport numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitimport warningswarnings.filterwarnings( \"ignore\" ) # to compare our model's accuracy with sklearn modelfrom sklearn.linear_model import LogisticRegression# Logistic Regressionclass LogitRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : A = 1 / ( 1 + np.exp( - ( self.X.dot( self.W ) + self.b ) ) ) # calculate gradients tmp = ( A - self.Y.T ) tmp = np.reshape( tmp, self.m ) dW = np.dot( self.X.T, tmp ) / self.m db = np.sum( tmp ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : Z = 1 / ( 1 + np.exp( - ( X.dot( self.W ) + self.b ) ) ) Y = np.where( Z > 0.5, 1, 0 ) return Y # Driver code def main() : # Importing dataset df = pd.read_csv( \"diabetes.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training model = LogitRegression( learning_rate = 0.01, iterations = 1000 ) model.fit( X_train, Y_train ) model1 = LogisticRegression() model1.fit( X_train, Y_train) # Prediction on test set Y_pred = model.predict( X_test ) Y_pred1 = model1.predict( X_test ) # measure performance correctly_classified = 0 correctly_classified1 = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 if Y_test[count] == Y_pred1[count] : correctly_classified1 = correctly_classified1 + 1 count = count + 1 print( \"Accuracy on test set by our model : \", ( correctly_classified / count ) * 100 ) print( \"Accuracy on test set by sklearn model : \", ( correctly_classified1 / count ) * 100 ) if __name__ == \"__main__\" : main()", "e": 30794, "s": 27658, "text": null }, { "code": null, "e": 30921, "s": 30794, "text": "Accuracy on test set by our model : 58.333333333333336\nAccuracy on test set by sklearn model : 61.111111111111114\n" }, { "code": null, "e": 31029, "s": 30921, "text": "Note: The above-trained model is to implement the mathematical intuition not just for improving accuracies." }, { "code": null, "e": 31046, "s": 31029, "text": "Machine Learning" }, { "code": null, "e": 31053, "s": 31046, "text": "Python" }, { "code": null, "e": 31070, "s": 31053, "text": "Machine Learning" }, { "code": null, "e": 31168, "s": 31070, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31209, "s": 31168, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 31242, "s": 31209, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31270, "s": 31242, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 31306, "s": 31270, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 31361, "s": 31306, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 31389, "s": 31361, "text": "Read JSON file using Python" }, { "code": null, "e": 31439, "s": 31389, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31461, "s": 31439, "text": "Python map() function" } ]
Dart - Comments - GeeksforGeeks
12 Nov, 2021 In every programming language comments play an important role for a better understanding of the code in the future or by any other programmer. Comments are a set of statements that are not meant to be executed by the compiler. They provide proper documentation of the code. Types of Dart Comments: Dart Single line Comment.Dart Multiline Comment.Dart Documentation Comment. Dart Single line Comment. Dart Multiline Comment. Dart Documentation Comment. 1. Dart Single line Comment: Dart single line comment is used to comment a line until line break occurs. It is done using a double forward-slash (//). // This is a single line comment. Example: Dart int main(){ double area = 3.14 * 4 * 4; // It prints the area // of a circle of radius = 4 print(area); return 0;} Output: 50.24 2. Dart Multi-Line Comment: Dart Multiline comment is used to comment out a whole section of code. It uses ‘/*’ and ‘*/’ to start and end a multi-line comment respectively. /* These are multiple line of comments */ Example: Dart int main(){ var lst = [1, 2, 3]; /* It prints the whole list at once */ print(lst); return 0; } Output: [1, 2, 3] 3. Dart Documentation Comment: Dart Documentation Comments are a special type of comment used to provide references to packages, software, or projects.Dart supports two types of documentation comments “///”(C# Style) and “/**.....*/”(JavaDoc Style). It is preferred to use “///” for doc comments as many times * is used to mark list items in a bulleted list which makes it difficult to read the comments. Doc comments are recommended for writing public APIs. /// This is /// a documentation /// comment Example: Dart bool checkEven(n){ /// Returns true /// if n is even if(n%2==0) return true; /// Returns false if n is odd else return false; } int main(){ int n = 43; print(checkEven(n)); return 0;} Output: false prachisoda1234 Dart-basics Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter Flutter - Managing the MediaQuery Object What is widgets in Flutter?
[ { "code": null, "e": 25285, "s": 25257, "text": "\n12 Nov, 2021" }, { "code": null, "e": 25560, "s": 25285, "text": "In every programming language comments play an important role for a better understanding of the code in the future or by any other programmer. Comments are a set of statements that are not meant to be executed by the compiler. They provide proper documentation of the code. " }, { "code": null, "e": 25585, "s": 25560, "text": "Types of Dart Comments: " }, { "code": null, "e": 25661, "s": 25585, "text": "Dart Single line Comment.Dart Multiline Comment.Dart Documentation Comment." }, { "code": null, "e": 25687, "s": 25661, "text": "Dart Single line Comment." }, { "code": null, "e": 25711, "s": 25687, "text": "Dart Multiline Comment." }, { "code": null, "e": 25739, "s": 25711, "text": "Dart Documentation Comment." }, { "code": null, "e": 25891, "s": 25739, "text": "1. Dart Single line Comment: Dart single line comment is used to comment a line until line break occurs. It is done using a double forward-slash (//). " }, { "code": null, "e": 25926, "s": 25891, "text": "// This is a single line comment. " }, { "code": null, "e": 25936, "s": 25926, "text": "Example: " }, { "code": null, "e": 25941, "s": 25936, "text": "Dart" }, { "code": "int main(){ double area = 3.14 * 4 * 4; // It prints the area // of a circle of radius = 4 print(area); return 0;}", "e": 26060, "s": 25941, "text": null }, { "code": null, "e": 26070, "s": 26062, "text": "Output:" }, { "code": null, "e": 26076, "s": 26070, "text": "50.24" }, { "code": null, "e": 26250, "s": 26076, "text": "2. Dart Multi-Line Comment: Dart Multiline comment is used to comment out a whole section of code. It uses ‘/*’ and ‘*/’ to start and end a multi-line comment respectively. " }, { "code": null, "e": 26301, "s": 26250, "text": "/* \n\nThese are \n\nmultiple line \n\nof comments \n\n*/ " }, { "code": null, "e": 26311, "s": 26301, "text": "Example: " }, { "code": null, "e": 26316, "s": 26311, "text": "Dart" }, { "code": "int main(){ var lst = [1, 2, 3]; /* It prints the whole list at once */ print(lst); return 0; }", "e": 26424, "s": 26316, "text": null }, { "code": null, "e": 26435, "s": 26426, "text": "Output: " }, { "code": null, "e": 26445, "s": 26435, "text": "[1, 2, 3]" }, { "code": null, "e": 26905, "s": 26445, "text": "3. Dart Documentation Comment: Dart Documentation Comments are a special type of comment used to provide references to packages, software, or projects.Dart supports two types of documentation comments “///”(C# Style) and “/**.....*/”(JavaDoc Style). It is preferred to use “///” for doc comments as many times * is used to mark list items in a bulleted list which makes it difficult to read the comments. Doc comments are recommended for writing public APIs. " }, { "code": null, "e": 26954, "s": 26905, "text": "/// This is \n\n/// a documentation \n\n/// comment " }, { "code": null, "e": 26964, "s": 26954, "text": "Example: " }, { "code": null, "e": 26969, "s": 26964, "text": "Dart" }, { "code": "bool checkEven(n){ /// Returns true /// if n is even if(n%2==0) return true; /// Returns false if n is odd else return false; } int main(){ int n = 43; print(checkEven(n)); return 0;}", "e": 27173, "s": 26969, "text": null }, { "code": null, "e": 27184, "s": 27175, "text": "Output: " }, { "code": null, "e": 27190, "s": 27184, "text": "false" }, { "code": null, "e": 27205, "s": 27190, "text": "prachisoda1234" }, { "code": null, "e": 27217, "s": 27205, "text": "Dart-basics" }, { "code": null, "e": 27222, "s": 27217, "text": "Dart" }, { "code": null, "e": 27320, "s": 27222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27359, "s": 27320, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27385, "s": 27359, "text": "ListView Class in Flutter" }, { "code": null, "e": 27411, "s": 27385, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27434, "s": 27411, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27452, "s": 27434, "text": "Flutter - Dialogs" }, { "code": null, "e": 27497, "s": 27452, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 27525, "s": 27497, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 27549, "s": 27525, "text": "Format Dates in Flutter" }, { "code": null, "e": 27590, "s": 27549, "text": "Flutter - Managing the MediaQuery Object" } ]
Create a shortcut key to activate an element in HTML
To create a shortcut key, use the access attribute in HTML. Let us say you need to add a shortcut key to the following link Hadoop Tutorial To let shortcut keys work correctly on Firefox web browser (Windows), you need to add it like this − [Alt] [Shift] + accesskey You can try to run the following code to create a shortcut key to activate an element in HTML − <!DOCTYPE html> <html> <body> <a href="https://www.tutorialspoint.com/hadoop/index.htm" accesskey="h">Hadoop Tutorial</a> <p>We have set ALT+SHIFT+H to access the Hadoop Tutorial</p> </body> </html>
[ { "code": null, "e": 1186, "s": 1062, "text": "To create a shortcut key, use the access attribute in HTML. Let us say you need to add a shortcut key to the following link" }, { "code": null, "e": 1202, "s": 1186, "text": "Hadoop Tutorial" }, { "code": null, "e": 1303, "s": 1202, "text": "To let shortcut keys work correctly on Firefox web browser (Windows), you need to add it like this −" }, { "code": null, "e": 1329, "s": 1303, "text": "[Alt] [Shift] + accesskey" }, { "code": null, "e": 1425, "s": 1329, "text": "You can try to run the following code to create a shortcut key to activate an element in HTML −" }, { "code": null, "e": 1642, "s": 1425, "text": "<!DOCTYPE html>\n<html>\n <body>\n <a href=\"https://www.tutorialspoint.com/hadoop/index.htm\" accesskey=\"h\">Hadoop Tutorial</a>\n <p>We have set ALT+SHIFT+H to access the Hadoop Tutorial</p>\n </body>\n</html>" } ]
Redis - Sorted Set Zinterstore Command
Redis ZINTERSTORE command computes the intersection of numkeys sorted sets given by the specified keys, and stores the result in the destination. It is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments. Integer reply, the number of elements in the resulting sorted set at the destination. Following is the basic syntax of Redis ZINTERSTORE command. redis 127.0.0.1:6379> ZINTERSTORE KEY INCREMENT MEMBER redis 127.0.0.1:6379> ZADD myset 1 "hello" (integer) 1 redis 127.0.0.1:6379> ZADD myset 2 "world" (integer) 1 redis 127.0.0.1:6379> ZADD myset2 1 "hello" (integer) 1 redis 127.0.0.1:6379> ZADD myset2 2 "world" (integer) 1 redis 127.0.0.1:6379> ZADD myset2 3 "foo" (integer) 1 redis 127.0.0.1:6379> ZINTERSTORE out 2 myset1 myset2 WEIGHTS 2 3" (integer) 3 redis 127.0.0.1:6379> ZRANGE out 0 -1 WITHSCORES 1) "hello" 2) "5" 3) "world" 4) "10" 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2319, "s": 2045, "text": "Redis ZINTERSTORE command computes the intersection of numkeys sorted sets given by the specified keys, and stores the result in the destination. It is mandatory to provide the number of input keys (numkeys) before passing the input keys and the other (optional) arguments." }, { "code": null, "e": 2405, "s": 2319, "text": "Integer reply, the number of elements in the resulting sorted set at the destination." }, { "code": null, "e": 2465, "s": 2405, "text": "Following is the basic syntax of Redis ZINTERSTORE command." }, { "code": null, "e": 2521, "s": 2465, "text": "redis 127.0.0.1:6379> ZINTERSTORE KEY INCREMENT MEMBER\n" }, { "code": null, "e": 2980, "s": 2521, "text": "redis 127.0.0.1:6379> ZADD myset 1 \"hello\" \n(integer) 1 \nredis 127.0.0.1:6379> ZADD myset 2 \"world\" \n(integer) 1 \nredis 127.0.0.1:6379> ZADD myset2 1 \"hello\" \n(integer) 1 \nredis 127.0.0.1:6379> ZADD myset2 2 \"world\" \n(integer) 1 \nredis 127.0.0.1:6379> ZADD myset2 3 \"foo\" \n(integer) 1 \nredis 127.0.0.1:6379> ZINTERSTORE out 2 myset1 myset2 WEIGHTS 2 3\" \n(integer) 3 \nredis 127.0.0.1:6379> ZRANGE out 0 -1 WITHSCORES \n1) \"hello\" \n2) \"5\" \n3) \"world\" \n4) \"10\" \n" }, { "code": null, "e": 3012, "s": 2980, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 3032, "s": 3012, "text": " Skillbakerystudios" }, { "code": null, "e": 3039, "s": 3032, "text": " Print" }, { "code": null, "e": 3050, "s": 3039, "text": " Add Notes" } ]
DateTime.GetDateTimeFormats() Method in C#
The DateTime.GetDateTimeFormats() method in C# is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers. Following is the syntax − public string[] GetDateTimeFormats () public string[] GetDateTimeFormats (char ch); Above, ch is a standard date and time format string. Let us now see an example to implement the DateTime.GetDateTimeFormats() method − using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 11, 10, 7, 20, 45); string[] res = d.GetDateTimeFormats(); foreach(string s in res) Console.WriteLine(s); } } This will produce the following output − 11/10/2019 11/10/19 11/10/19 11/10/2019 19/11/10 2019-11-10 10-Nov-19 Sunday, November 10, 2019 November 10, 2019 Sunday, 10 November, 2019 10 November, 2019 Sunday, November 10, 2019 7:20 AM Sunday, November 10, 2019 07:20 AM Sunday, November 10, 2019 7:20 Sunday, November 10, 2019 07:20 November 10, 2019 7:20 AM November 10, 2019 07:20 AM November 10, 2019 7:20 November 10, 2019 07:20 Sunday, 10 November, 2019 7:20 AM Sunday, 10 November, 2019 07:20 AM Sunday, 10 November, 2019 7:20 Sunday, 10 November, 2019 07:20 10 November, 2019 7:20 AM 10 November, 2019 07:20 AM 10 November, 2019 7:20 10 November, 2019 07:20 Sunday, November 10, 2019 7:20:45 AM Sunday, November 10, 2019 07:20:45 AM Sunday, November 10, 2019 7:20:45 Sunday, November 10, 2019 07:20:45 November 10, 2019 7:20:45 AM November 10, 2019 07:20:45 AM November 10, 2019 7:20:45 November 10, 2019 07:20:45 Sunday, 10 November, 2019 7:20:45 AM Sunday, 10 November, 2019 07:20:45 AM Sunday, 10 November, 2019 7:20:45 Sunday, 10 November, 2019 07:20:45 10 November, 2019 7:20:45 AM 10 November, 2019 07:20:45 AM 10 November, 2019 7:20:45 10 November, 2019 07:20:45 11/10/2019 7:20 AM 11/10/2019 07:20 AM 11/10/2019 7:20 11/10/2019 07:20 11/10/19 7:20 AM 11/10/19 07:20 AM 11/10/19 7:20 11/10/19 07:20 11/10/19 7:20 AM 11/10/19 07:20 AM 11/10/19 7:20 11/10/19 07:20 11/10/2019 7:20 AM 11/10/2019 07:20 AM 11/10/2019 7:20 11/10/2019 07:20 19/11/10 7:20 AM 19/11/10 07:20 AM 19/11/10 7:20 19/11/10 07:20 2019-11-10 7:20 AM 2019-11-10 07:20 AM 2019-11-10 7:20 2019-11-10 07:20 10-Nov-19 7:20 AM 10-Nov-19 07:20 AM 10-Nov-19 7:20 10-Nov-19 07:20 11/10/2019 7:20:45 AM 11/10/2019 07:20:45 AM 11/10/2019 7:20:45 11/10/2019 07:20:45 11/10/19 7:20:45 AM 11/10/19 07:20:45 AM 11/10/19 7:20:45 11/10/19 07:20:45 11/10/19 7:20:45 AM 11/10/19 07:20:45 AM 11/10/19 7:20:45 11/10/19 07:20:45 11/10/2019 7:20:45 AM 11/10/2019 07:20:45 AM 11/10/2019 7:20:45 11/10/2019 07:20:45 19/11/10 7:20:45 AM 19/11/10 07:20:45 AM 19/11/10 7:20:45 19/11/10 07:20:45 2019-11-10 7:20:45 AM 2019-11-10 07:20:45 AM 2019-11-10 7:20:45 2019-11-10 07:20:45 10-Nov-19 7:20:45 AM 10-Nov-19 07:20:45 AM 10-Nov-19 7:20:45 10-Nov-19 07:20:45 November 10 November 10 2019-11-10T07:20:45.0000000 2019-11-10T07:20:45.0000000 Sun, 10 Nov 2019 07:20:45 GMT Sun, 10 Nov 2019 07:20:45 GMT 2019-11-10T07:20:45 7:20 AM 07:20 AM 7:20 07:20 7:20:45 AM 07:20:45 AM 7:20:45 07:20:45 2019-11-10 07:20:45Z Sunday, November 10, 2019 7:20:45 AM Sunday, November 10, 2019 07:20:45 AM Sunday, November 10, 2019 7:20:45 Sunday, November 10, 2019 07:20:45 November 10, 2019 7:20:45 AM November 10, 2019 07:20:45 AM November 10, 2019 7:20:45 November 10, 2019 07:20:45 Sunday, 10 November, 2019 7:20:45 AM Sunday, 10 November, 2019 07:20:45 AM Sunday, 10 November, 2019 7:20:45 Sunday, 10 November, 2019 07:20:45 10 November, 2019 7:20:45 AM 10 November, 2019 07:20:45 AM 10 November, 2019 7:20:45 10 November, 2019 07:20:45 November 2019 November 2019 Let us now see another example to implement the DateTime.GetDateTimeFormats() method. For char format, we use format specifiers like "d" for Short date pattern, "D" for Long date pattern, “F” for Full date/time pattern (long time), etc, using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 11, 10, 7, 20, 45); string[] res = d.GetDateTimeFormats('F'); foreach(string s in res) Console.WriteLine(s); } } This will produce the following output − Sunday, November 10, 2019 7:20:45 AM Sunday, November 10, 2019 07:20:45 AM Sunday, November 10, 2019 7:20:45 Sunday, November 10, 2019 07:20:45 November 10, 2019 7:20:45 AM November 10, 2019 07:20:45 AM November 10, 2019 7:20:45 November 10, 2019 07:20:45 Sunday, 10 November, 2019 7:20:45 AM Sunday, 10 November, 2019 07:20:45 AM Sunday, 10 November, 2019 7:20:45 Sunday, 10 November, 2019 07:20:45 10 November, 2019 7:20:45 AM 10 November, 2019 07:20:45 AM 10 November, 2019 7:20:45 10 November, 2019 07:20:45
[ { "code": null, "e": 1248, "s": 1062, "text": "The DateTime.GetDateTimeFormats() method in C# is used to convert the value of this instance to all the string representations supported by the standard date and time format specifiers." }, { "code": null, "e": 1274, "s": 1248, "text": "Following is the syntax −" }, { "code": null, "e": 1358, "s": 1274, "text": "public string[] GetDateTimeFormats ()\npublic string[] GetDateTimeFormats (char ch);" }, { "code": null, "e": 1411, "s": 1358, "text": "Above, ch is a standard date and time format string." }, { "code": null, "e": 1493, "s": 1411, "text": "Let us now see an example to implement the DateTime.GetDateTimeFormats() method −" }, { "code": null, "e": 1727, "s": 1493, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 11, 10, 7, 20, 45);\n string[] res = d.GetDateTimeFormats();\n foreach(string s in res)\n Console.WriteLine(s);\n }\n}" }, { "code": null, "e": 1768, "s": 1727, "text": "This will produce the following output −" }, { "code": null, "e": 4727, "s": 1768, "text": "11/10/2019\n11/10/19\n11/10/19\n11/10/2019\n19/11/10\n2019-11-10\n10-Nov-19\nSunday, November 10, 2019\nNovember 10, 2019\nSunday, 10 November, 2019\n10 November, 2019\nSunday, November 10, 2019 7:20 AM\nSunday, November 10, 2019 07:20 AM\nSunday, November 10, 2019 7:20\nSunday, November 10, 2019 07:20\nNovember 10, 2019 7:20 AM\nNovember 10, 2019 07:20 AM\nNovember 10, 2019 7:20\nNovember 10, 2019 07:20\nSunday, 10 November, 2019 7:20 AM\nSunday, 10 November, 2019 07:20 AM\nSunday, 10 November, 2019 7:20\nSunday, 10 November, 2019 07:20\n10 November, 2019 7:20 AM\n10 November, 2019 07:20 AM\n10 November, 2019 7:20\n10 November, 2019 07:20\nSunday, November 10, 2019 7:20:45 AM\nSunday, November 10, 2019 07:20:45 AM\nSunday, November 10, 2019 7:20:45\nSunday, November 10, 2019 07:20:45\nNovember 10, 2019 7:20:45 AM\nNovember 10, 2019 07:20:45 AM\nNovember 10, 2019 7:20:45\nNovember 10, 2019 07:20:45\nSunday, 10 November, 2019 7:20:45 AM\nSunday, 10 November, 2019 07:20:45 AM\nSunday, 10 November, 2019 7:20:45\nSunday, 10 November, 2019 07:20:45\n10 November, 2019 7:20:45 AM\n10 November, 2019 07:20:45 AM\n10 November, 2019 7:20:45\n10 November, 2019 07:20:45\n11/10/2019 7:20 AM\n11/10/2019 07:20 AM\n11/10/2019 7:20\n11/10/2019 07:20\n11/10/19 7:20 AM\n11/10/19 07:20 AM\n11/10/19 7:20\n11/10/19 07:20\n11/10/19 7:20 AM\n11/10/19 07:20 AM\n11/10/19 7:20\n11/10/19 07:20\n11/10/2019 7:20 AM\n11/10/2019 07:20 AM\n11/10/2019 7:20\n11/10/2019 07:20\n19/11/10 7:20 AM\n19/11/10 07:20 AM\n19/11/10 7:20\n19/11/10 07:20\n2019-11-10 7:20 AM\n2019-11-10 07:20 AM\n2019-11-10 7:20\n2019-11-10 07:20\n10-Nov-19 7:20 AM\n10-Nov-19 07:20 AM\n10-Nov-19 7:20\n10-Nov-19 07:20\n11/10/2019 7:20:45 AM\n11/10/2019 07:20:45 AM\n11/10/2019 7:20:45\n11/10/2019 07:20:45\n11/10/19 7:20:45 AM\n11/10/19 07:20:45 AM\n11/10/19 7:20:45\n11/10/19 07:20:45\n11/10/19 7:20:45 AM\n11/10/19 07:20:45 AM\n11/10/19 7:20:45\n11/10/19 07:20:45\n11/10/2019 7:20:45 AM\n11/10/2019 07:20:45 AM\n11/10/2019 7:20:45\n11/10/2019 07:20:45\n19/11/10 7:20:45 AM\n19/11/10 07:20:45 AM\n19/11/10 7:20:45\n19/11/10 07:20:45\n2019-11-10 7:20:45 AM\n2019-11-10 07:20:45 AM\n2019-11-10 7:20:45\n2019-11-10 07:20:45\n10-Nov-19 7:20:45 AM\n10-Nov-19 07:20:45 AM\n10-Nov-19 7:20:45\n10-Nov-19 07:20:45\nNovember 10\nNovember 10\n2019-11-10T07:20:45.0000000\n2019-11-10T07:20:45.0000000\nSun, 10 Nov 2019 07:20:45 GMT\nSun, 10 Nov 2019 07:20:45 GMT\n2019-11-10T07:20:45\n7:20 AM\n07:20 AM\n7:20\n07:20\n7:20:45 AM\n07:20:45 AM\n7:20:45\n07:20:45\n2019-11-10 07:20:45Z\nSunday, November 10, 2019 7:20:45 AM\nSunday, November 10, 2019 07:20:45 AM\nSunday, November 10, 2019 7:20:45\nSunday, November 10, 2019 07:20:45\nNovember 10, 2019 7:20:45 AM\nNovember 10, 2019 07:20:45 AM\nNovember 10, 2019 7:20:45\nNovember 10, 2019 07:20:45\nSunday, 10 November, 2019 7:20:45 AM\nSunday, 10 November, 2019 07:20:45 AM\nSunday, 10 November, 2019 7:20:45\nSunday, 10 November, 2019 07:20:45\n10 November, 2019 7:20:45 AM\n10 November, 2019 07:20:45 AM\n10 November, 2019 7:20:45\n10 November, 2019 07:20:45\nNovember 2019\nNovember 2019" }, { "code": null, "e": 4964, "s": 4727, "text": "Let us now see another example to implement the DateTime.GetDateTimeFormats() method. For char format, we use format specifiers like \"d\" for Short date pattern, \"D\" for Long date pattern, “F” for Full date/time pattern (long time), etc," }, { "code": null, "e": 5201, "s": 4964, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 11, 10, 7, 20, 45);\n string[] res = d.GetDateTimeFormats('F');\n foreach(string s in res)\n Console.WriteLine(s);\n }\n}" }, { "code": null, "e": 5242, "s": 5201, "text": "This will produce the following output −" }, { "code": null, "e": 5754, "s": 5242, "text": "Sunday, November 10, 2019 7:20:45 AM\nSunday, November 10, 2019 07:20:45 AM\nSunday, November 10, 2019 7:20:45\nSunday, November 10, 2019 07:20:45\nNovember 10, 2019 7:20:45 AM\nNovember 10, 2019 07:20:45 AM\nNovember 10, 2019 7:20:45\nNovember 10, 2019 07:20:45\nSunday, 10 November, 2019 7:20:45 AM\nSunday, 10 November, 2019 07:20:45 AM\nSunday, 10 November, 2019 7:20:45\nSunday, 10 November, 2019 07:20:45\n10 November, 2019 7:20:45 AM\n10 November, 2019 07:20:45 AM\n10 November, 2019 7:20:45\n10 November, 2019 07:20:45" } ]
How to get first day of week in PHP? - GeeksforGeeks
07 Feb, 2019 Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.Syntax: strtotime($EnglishDateTime, $time_now) Parameters: The strtotime() function accepts two parameters as mentioned above and described below: $EnglishDateTime: It specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns the time in seconds. It is required parameter. $time_now: This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter. date() Function: The date() function returns more understandable and human readable format of date.Syntax: date( format, timestamp ) Parameters: This function accepts two parameters as mentioned above and described below: format: It specify the format for date and time in which the result will be display. timestamp: It is the default time variable from which the date will be generated. Note: In PHP, the week starts with Monday, so if the time-string is given as “this week” the output will be timestamp of Monday which can make readable by passing it through date() function. Program 1: Get the default first day of a week when the time-string is “this week”. <?php // PHP program to print default first// day of current week // l will display the name of the day // d, m, Y will display the day, month// and year respectively $firstday = date('l - d/m/Y', strtotime("this week")); echo "First day of this week: ", $firstday; ?> First day of this week: Monday - 04/02/2019 Now, Usually Sunday is considered as the first day of a week. So, in PHP to get the Sunday of as first day of a week, consider the Sunday of previous week. That is to get the first day (Sunday) of a week need to get the Sunday of previous week and to get the first day (Sunday) of next week need to get the Sunday of this week and so on.PHP supports -ve indexing in time-string. So, in order to get the previous week it can use the time string as “-1 week” and to get the day it can also have to include the name of the day in time string. Program 2: Get the first day (Sunday) of the week. <?php // PHP program to display sunday as first day of a week // l will display the name of the day// d, m and Y will display the day, month and year respectively // For current week the time-string will be "sunday -1 week"// here -1 denotes last week$firstday = date('l - d/m/Y', strtotime("sunday -1 week"));echo "First day of this week: ", $firstday, "\n"; // For previous week the time-string wil be "sunday -2 week"// here -2 denotes week before last week$firstday = date('l - d/m/Y', strtotime("sunday -2 week"));echo "First day of last week: ", $firstday, "\n"; // For next week the time-string wil be "sunday 0 week"// here 0 denotes this week$firstday = date('l - d/m/Y', strtotime("sunday 0 week"));echo "First day of next week: ", $firstday, "\n"; // For week after next week the time-string wil be "sunday 1 week"// here 1 denotes next week$firstday = date('l - d/m/Y', strtotime("sunday 1 week"));echo "First day of week after next week : ", $firstday; ?> First day of this week: Sunday - 03/02/2019 First day of last week: Sunday - 27/01/2019 First day of next week: Sunday - 10/02/2019 First day of week after next week : Sunday - 17/02/2019 Picked PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? Comparing two dates in PHP How to receive JSON POST with PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to Upload Image into Database and Display it using PHP ? Comparing two dates in PHP
[ { "code": null, "e": 24640, "s": 24612, "text": "\n07 Feb, 2019" }, { "code": null, "e": 24844, "s": 24640, "text": "Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date." }, { "code": null, "e": 24958, "s": 24844, "text": "strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.Syntax:" }, { "code": null, "e": 24997, "s": 24958, "text": "strtotime($EnglishDateTime, $time_now)" }, { "code": null, "e": 25097, "s": 24997, "text": "Parameters: The strtotime() function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 25311, "s": 25097, "text": "$EnglishDateTime: It specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns the time in seconds. It is required parameter." }, { "code": null, "e": 25428, "s": 25311, "text": "$time_now: This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter." }, { "code": null, "e": 25535, "s": 25428, "text": "date() Function: The date() function returns more understandable and human readable format of date.Syntax:" }, { "code": null, "e": 25561, "s": 25535, "text": "date( format, timestamp )" }, { "code": null, "e": 25650, "s": 25561, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 25735, "s": 25650, "text": "format: It specify the format for date and time in which the result will be display." }, { "code": null, "e": 25817, "s": 25735, "text": "timestamp: It is the default time variable from which the date will be generated." }, { "code": null, "e": 26008, "s": 25817, "text": "Note: In PHP, the week starts with Monday, so if the time-string is given as “this week” the output will be timestamp of Monday which can make readable by passing it through date() function." }, { "code": null, "e": 26092, "s": 26008, "text": "Program 1: Get the default first day of a week when the time-string is “this week”." }, { "code": "<?php // PHP program to print default first// day of current week // l will display the name of the day // d, m, Y will display the day, month// and year respectively $firstday = date('l - d/m/Y', strtotime(\"this week\")); echo \"First day of this week: \", $firstday; ?>", "e": 26366, "s": 26092, "text": null }, { "code": null, "e": 26411, "s": 26366, "text": "First day of this week: Monday - 04/02/2019\n" }, { "code": null, "e": 26951, "s": 26411, "text": "Now, Usually Sunday is considered as the first day of a week. So, in PHP to get the Sunday of as first day of a week, consider the Sunday of previous week. That is to get the first day (Sunday) of a week need to get the Sunday of previous week and to get the first day (Sunday) of next week need to get the Sunday of this week and so on.PHP supports -ve indexing in time-string. So, in order to get the previous week it can use the time string as “-1 week” and to get the day it can also have to include the name of the day in time string." }, { "code": null, "e": 27002, "s": 26951, "text": "Program 2: Get the first day (Sunday) of the week." }, { "code": "<?php // PHP program to display sunday as first day of a week // l will display the name of the day// d, m and Y will display the day, month and year respectively // For current week the time-string will be \"sunday -1 week\"// here -1 denotes last week$firstday = date('l - d/m/Y', strtotime(\"sunday -1 week\"));echo \"First day of this week: \", $firstday, \"\\n\"; // For previous week the time-string wil be \"sunday -2 week\"// here -2 denotes week before last week$firstday = date('l - d/m/Y', strtotime(\"sunday -2 week\"));echo \"First day of last week: \", $firstday, \"\\n\"; // For next week the time-string wil be \"sunday 0 week\"// here 0 denotes this week$firstday = date('l - d/m/Y', strtotime(\"sunday 0 week\"));echo \"First day of next week: \", $firstday, \"\\n\"; // For week after next week the time-string wil be \"sunday 1 week\"// here 1 denotes next week$firstday = date('l - d/m/Y', strtotime(\"sunday 1 week\"));echo \"First day of week after next week : \", $firstday; ?>", "e": 27978, "s": 27002, "text": null }, { "code": null, "e": 28167, "s": 27978, "text": "First day of this week: Sunday - 03/02/2019\nFirst day of last week: Sunday - 27/01/2019\nFirst day of next week: Sunday - 10/02/2019\nFirst day of week after next week : Sunday - 17/02/2019\n" }, { "code": null, "e": 28174, "s": 28167, "text": "Picked" }, { "code": null, "e": 28178, "s": 28174, "text": "PHP" }, { "code": null, "e": 28191, "s": 28178, "text": "PHP Programs" }, { "code": null, "e": 28208, "s": 28191, "text": "Web Technologies" }, { "code": null, "e": 28212, "s": 28208, "text": "PHP" }, { "code": null, "e": 28310, "s": 28212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28360, "s": 28310, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28400, "s": 28360, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28461, "s": 28400, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28488, "s": 28461, "text": "Comparing two dates in PHP" }, { "code": null, "e": 28524, "s": 28488, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 28574, "s": 28524, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28614, "s": 28574, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28666, "s": 28614, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28727, "s": 28666, "text": "How to Upload Image into Database and Display it using PHP ?" } ]
Find the sum of N terms of the series 1, 4, 13, 40, 121, ... - GeeksforGeeks
21 Jan, 2022 Given a positive integer, n. Find the sum of the first n term of the series: 1, 4, 13, 40, 121, ..... Examples: Input: n = 5Output: 179 Input: n = 3Output: 18 Approach: The sequence is formed by using the following pattern. For any value N- The above solution can be derived following the series of steps- Let Tn be the nth term and Sn be the sum to n terms of the given series. Thus, we have -(1) Equation (1) can be written as- S_{n}=1+4+13+40+121+...+T_{n-1}+T_{n} -(2) Subtracting equation (2) from equation (1), we get The above equation 3, 9, 27, 81, ... is a G.P. with common ratio 3 and first term 3. Thus, we have Since, Therefore, Thus, sum of n terms is Illustration: Input: n = 5Output: 179Explanation: = = =179 Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return sum of// first N term of the seriesint findSum(int N){ return (pow(3, N + 1) - 3 - 2 * N) / 4;} // Driver Codeint main(){ int N = 5; cout << findSum(N); return 0;} // Java program for the above approachimport java.util.*;public class GFG{ // Function to return sum of // first N term of the series static int findSum(int N) { return (int)(Math.pow(3, N + 1) - 3 - 2 * N) / 4; } public static void main(String args[]) { int N = 5; System.out.print(findSum(N)); }}// This code is contributed by Samim Hossain Mondal. # Python code for the above approach # Function to return sum of# first N term of the seriesdef findSum(N): return (3 ** (N + 1) - 3 - 2 * N) // 4; # Driver CodeN = 5;print(findSum(N)); # This code is contributed by Saurabh Jaiswal // C# program to implement// the above approachusing System;class GFG{ // Function to return sum of// first N term of the seriesstatic int findSum(int N){ return (int)(Math.Pow(3, N + 1) - 3 - 2 * N) / 4;} // Driver Code public static void Main() { int N = 5; Console.Write(findSum(N)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to return sum of // first N term of the series function findSum(N) { return Math.floor((Math.pow(3, N + 1) - 3 - 2 * N) / 4); } // Driver Code let N = 5; document.write(findSum(N)); // This code is contributed by Potta Lokesh </script> 179 Time Complexity: O(1) Auxiliary Space: O(1) lokeshpotta20 samim2000 _saurabh_jaiswal Algo-Geek 2021 series Algo Geek Mathematical Pattern Searching Mathematical series Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of operation required to water all the plants Check if the given string is valid English word or not Lexicographically smallest string formed by concatenating any prefix and its mirrored form Encode given String by inserting in Matrix column-wise and printing it row-wise Minimum count of words among all the given sentences Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26350, "s": 26322, "text": "\n21 Jan, 2022" }, { "code": null, "e": 26427, "s": 26350, "text": "Given a positive integer, n. Find the sum of the first n term of the series:" }, { "code": null, "e": 26452, "s": 26427, "text": "1, 4, 13, 40, 121, ....." }, { "code": null, "e": 26462, "s": 26452, "text": "Examples:" }, { "code": null, "e": 26486, "s": 26462, "text": "Input: n = 5Output: 179" }, { "code": null, "e": 26509, "s": 26486, "text": "Input: n = 3Output: 18" }, { "code": null, "e": 26519, "s": 26509, "text": "Approach:" }, { "code": null, "e": 26591, "s": 26519, "text": "The sequence is formed by using the following pattern. For any value N-" }, { "code": null, "e": 26656, "s": 26591, "text": "The above solution can be derived following the series of steps-" }, { "code": null, "e": 26729, "s": 26656, "text": "Let Tn be the nth term and Sn be the sum to n terms of the given series." }, { "code": null, "e": 26743, "s": 26729, "text": "Thus, we have" }, { "code": null, "e": 26750, "s": 26743, "text": " -(1)" }, { "code": null, "e": 26782, "s": 26750, "text": "Equation (1) can be written as-" }, { "code": null, "e": 26826, "s": 26782, "text": "S_{n}=1+4+13+40+121+...+T_{n-1}+T_{n} -(2)" }, { "code": null, "e": 26877, "s": 26826, "text": "Subtracting equation (2) from equation (1), we get" }, { "code": null, "e": 26962, "s": 26877, "text": "The above equation 3, 9, 27, 81, ... is a G.P. with common ratio 3 and first term 3." }, { "code": null, "e": 26976, "s": 26962, "text": "Thus, we have" }, { "code": null, "e": 26983, "s": 26976, "text": "Since," }, { "code": null, "e": 26994, "s": 26983, "text": "Therefore," }, { "code": null, "e": 27018, "s": 26994, "text": "Thus, sum of n terms is" }, { "code": null, "e": 27032, "s": 27018, "text": "Illustration:" }, { "code": null, "e": 27095, "s": 27032, "text": "Input: n = 5Output: 179Explanation: = = =179" }, { "code": null, "e": 27146, "s": 27095, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27150, "s": 27146, "text": "C++" }, { "code": null, "e": 27155, "s": 27150, "text": "Java" }, { "code": null, "e": 27163, "s": 27155, "text": "Python3" }, { "code": null, "e": 27166, "s": 27163, "text": "C#" }, { "code": null, "e": 27177, "s": 27166, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return sum of// first N term of the seriesint findSum(int N){ return (pow(3, N + 1) - 3 - 2 * N) / 4;} // Driver Codeint main(){ int N = 5; cout << findSum(N); return 0;}", "e": 27483, "s": 27177, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to return sum of // first N term of the series static int findSum(int N) { return (int)(Math.pow(3, N + 1) - 3 - 2 * N) / 4; } public static void main(String args[]) { int N = 5; System.out.print(findSum(N)); }}// This code is contributed by Samim Hossain Mondal.", "e": 27869, "s": 27483, "text": null }, { "code": "# Python code for the above approach # Function to return sum of# first N term of the seriesdef findSum(N): return (3 ** (N + 1) - 3 - 2 * N) // 4; # Driver CodeN = 5;print(findSum(N)); # This code is contributed by Saurabh Jaiswal", "e": 28104, "s": 27869, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to return sum of// first N term of the seriesstatic int findSum(int N){ return (int)(Math.Pow(3, N + 1) - 3 - 2 * N) / 4;} // Driver Code public static void Main() { int N = 5; Console.Write(findSum(N)); }} // This code is contributed by Samim Hossain Mondal.", "e": 28477, "s": 28104, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to return sum of // first N term of the series function findSum(N) { return Math.floor((Math.pow(3, N + 1) - 3 - 2 * N) / 4); } // Driver Code let N = 5; document.write(findSum(N)); // This code is contributed by Potta Lokesh </script>", "e": 28841, "s": 28477, "text": null }, { "code": null, "e": 28848, "s": 28844, "text": "179" }, { "code": null, "e": 28872, "s": 28850, "text": "Time Complexity: O(1)" }, { "code": null, "e": 28896, "s": 28874, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 28912, "s": 28898, "text": "lokeshpotta20" }, { "code": null, "e": 28922, "s": 28912, "text": "samim2000" }, { "code": null, "e": 28939, "s": 28922, "text": "_saurabh_jaiswal" }, { "code": null, "e": 28954, "s": 28939, "text": "Algo-Geek 2021" }, { "code": null, "e": 28961, "s": 28954, "text": "series" }, { "code": null, "e": 28971, "s": 28961, "text": "Algo Geek" }, { "code": null, "e": 28984, "s": 28971, "text": "Mathematical" }, { "code": null, "e": 29002, "s": 28984, "text": "Pattern Searching" }, { "code": null, "e": 29015, "s": 29002, "text": "Mathematical" }, { "code": null, "e": 29022, "s": 29015, "text": "series" }, { "code": null, "e": 29040, "s": 29022, "text": "Pattern Searching" }, { "code": null, "e": 29138, "s": 29040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29190, "s": 29138, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 29245, "s": 29190, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 29336, "s": 29245, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 29416, "s": 29336, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 29469, "s": 29416, "text": "Minimum count of words among all the given sentences" }, { "code": null, "e": 29499, "s": 29469, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 29559, "s": 29499, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29574, "s": 29559, "text": "C++ Data Types" }, { "code": null, "e": 29617, "s": 29574, "text": "Set in C++ Standard Template Library (STL)" } ]
Convert a string to hexadecimal ASCII values
26 May, 2022 Given a string as input, write a program to convert the characters of the given string into the hexadecimal equivalent of ASCII values. Examples : Input : Geek Output : 4765656b Input : IronMan part 3 Output : 49726f6e4d616e20706172742033 ASCII stands for American Standard Code for Information Interchange. ASCII is a standard that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit code. E.g the lower case “h” character (Char) has a decimal value of 104, which is “01101000” in binary and “68” in hexadecimal.ASCII TABLEThe “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). Algorithm : Initialize final Hex string as empty.Consider every character from input, cast it into integer. This integer value is ascii value of that character.Change this integer value into hexadecimal value and add this hexadecimal value to final Hex string. Initialize final Hex string as empty. Consider every character from input, cast it into integer. This integer value is ascii value of that character. Change this integer value into hexadecimal value and add this hexadecimal value to final Hex string. Basic implementation of the above idea: C++ Java Python3 C# Javascript // C++ program to convert// ASCII string to Hexadecimal// format string// Function to convert// decimal to hexadecimal #include <iostream> using namespace std; // function to convert decimal to hexadecimalstring decToHexa(int n){ // char array to store hexadecimal number char hexaDeciNum[100]; // counter for hexadecimal number array int i = 0; while (n != 0) { // temporary variable to store remainder int temp = 0; // storing remainder in temp variable. temp = n % 16; // check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 55; i++; } n = n / 16; } string ans = ""; // printing hexadecimal number array in reverse order for (int j = i - 1; j >= 0; j--) ans += hexaDeciNum[j]; return ans;}// Function to convert ASCII to HEXstring ASCIItoHEX(string ascii){ // Initialize final String string hex = ""; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.length(); i++) { // Take a char from // position i of string char ch = ascii[i]; // Cast char to integer and // find its ascii value int tmp = (int)ch; // Change this ascii value // integer to hexadecimal value string part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex;}int main(){ // Driver code // Print the Hex String cout << (ASCIItoHEX("Geek"));} // this code is contributed by phasing17 // Java program to convert ASCII// string to Hexadecimal format stringimport java.util.Scanner; class ASCIItoHEX { // function to convert ASCII to HEX public static String ASCIItoHEX(String ascii) { // Initialize final String String hex = ""; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.length(); i++) { // take a char from // position i of string char ch = ascii.charAt(i); // cast char to integer and // find its ascii value int in = (int)ch; // change this ascii value // integer to hexadecimal value String part = Integer.toHexString(in); // add this hexadecimal value // to final string. hex += part; } // return the final string hex return hex; } // Driver Function public static void main(String arg[]) { // print the Hex String System.out.println(ASCIItoHEX("Geek")); }} # Python3 program to convert ASCII# string to Hexadecimal format string # function to convert ASCII to HEXdef ASCIItoHEX(ascii): # Initialize final String hexa = "" # Make a loop to iterate through # every character of ascii string for i in range(len(ascii)): # take a char from # position i of string ch = ascii[i] # cast char to integer and # find its ascii value in1 = ord(ch) # change this ascii value # integer to hexadecimal value part = hex(in1).lstrip("0x").rstrip("L") # add this hexadecimal value # to final string. hexa += part # return the final string hex return hexa # Driver Functionif __name__ == '__main__': # print the Hex String print(ASCIItoHEX("Geek")) # This code is contributed by pratham76 // C# program to convert// ASCII string to Hexadecimal// format stringusing System;class GFG{ // Function to convert// decimal to hexadecimalstatic string decToHexa(int n){ // char array to store // hexadecimal number char []hexaDeciNum = new char[100]; // counter for hexadecimal // number array int i = 0; while(n != 0) { // temporary variable // to store remainder int temp = 0; // Storing remainder // in temp variable. temp = n % 16; // Check if temp < 10 if(temp < 10) { hexaDeciNum[i] = (char)(temp + 48); i++; } else { hexaDeciNum[i] = (char)(temp + 87); i++; } n = n / 16; } string ans = ""; // Printing hexadecimal number // array in reverse order for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Function to convert ASCII to HEXpublic static string ASCIItoHEX(string ascii){ // Initialize final String string hex = ""; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.Length; i++) { // Take a char from // position i of string char ch = ascii[i]; // Cast char to integer and // find its ascii value int tmp = (int)ch; // Change this ascii value // integer to hexadecimal value string part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex;} // Driver codepublic static void Main(string []arg){ // Print the Hex String Console.Write(ASCIItoHEX("Geek"));}} // This code is contributed by rutvik_56 <script> // JavaScript program to convert // ASCII string to Hexadecimal // format string // Function to convert // decimal to hexadecimal function decToHexa(n) { // char array to store // hexadecimal number var hexaDeciNum = new Array(100).fill(0); // counter for hexadecimal // number array var i = 0; while (n !== 0) { // temporary variable // to store remainder var temp = 0; // Storing remainder // in temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = String.fromCharCode(temp + 48); i++; } else { hexaDeciNum[i] = String.fromCharCode(temp + 87); i++; } n = parseInt(n / 16); } var ans = ""; // Printing hexadecimal number // array in reverse order for (var j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans; } // Function to convert ASCII to HEX function ASCIItoHEX(ascii) { // Initialize final String var hex = ""; // Make a loop to iterate through // every character of ascii string for (var i = 0; i < ascii.length; i++) { // Take a char from // position i of string var ch = ascii[i]; // Cast char to integer and // find its ascii value var tmp = ch.charCodeAt(0); // Change this ascii value // integer to hexadecimal value var part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex; } // Driver code // Print the Hex String document.write(ASCIItoHEX("Geek")); </script> Output: 4765656b rutvik_56 pratham76 rdtank phasing17 Java-Strings Java Programs Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java Java program to count the occurrence of each character in a string using Hashmap How to Iterate HashMap in Java? Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 176, "s": 28, "text": "Given a string as input, write a program to convert the characters of the given string into the hexadecimal equivalent of ASCII values. Examples : " }, { "code": null, "e": 271, "s": 176, "text": "Input : Geek\nOutput : 4765656b \n\nInput : IronMan part 3\nOutput : 49726f6e4d616e20706172742033" }, { "code": null, "e": 844, "s": 271, "text": "ASCII stands for American Standard Code for Information Interchange. ASCII is a standard that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit code. E.g the lower case “h” character (Char) has a decimal value of 104, which is “01101000” in binary and “68” in hexadecimal.ASCII TABLEThe “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system. Hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15). " }, { "code": null, "e": 857, "s": 844, "text": "Algorithm : " }, { "code": null, "e": 1106, "s": 857, "text": "Initialize final Hex string as empty.Consider every character from input, cast it into integer. This integer value is ascii value of that character.Change this integer value into hexadecimal value and add this hexadecimal value to final Hex string." }, { "code": null, "e": 1144, "s": 1106, "text": "Initialize final Hex string as empty." }, { "code": null, "e": 1256, "s": 1144, "text": "Consider every character from input, cast it into integer. This integer value is ascii value of that character." }, { "code": null, "e": 1357, "s": 1256, "text": "Change this integer value into hexadecimal value and add this hexadecimal value to final Hex string." }, { "code": null, "e": 1399, "s": 1357, "text": "Basic implementation of the above idea: " }, { "code": null, "e": 1403, "s": 1399, "text": "C++" }, { "code": null, "e": 1408, "s": 1403, "text": "Java" }, { "code": null, "e": 1416, "s": 1408, "text": "Python3" }, { "code": null, "e": 1419, "s": 1416, "text": "C#" }, { "code": null, "e": 1430, "s": 1419, "text": "Javascript" }, { "code": "// C++ program to convert// ASCII string to Hexadecimal// format string// Function to convert// decimal to hexadecimal #include <iostream> using namespace std; // function to convert decimal to hexadecimalstring decToHexa(int n){ // char array to store hexadecimal number char hexaDeciNum[100]; // counter for hexadecimal number array int i = 0; while (n != 0) { // temporary variable to store remainder int temp = 0; // storing remainder in temp variable. temp = n % 16; // check if temp < 10 if (temp < 10) { hexaDeciNum[i] = temp + 48; i++; } else { hexaDeciNum[i] = temp + 55; i++; } n = n / 16; } string ans = \"\"; // printing hexadecimal number array in reverse order for (int j = i - 1; j >= 0; j--) ans += hexaDeciNum[j]; return ans;}// Function to convert ASCII to HEXstring ASCIItoHEX(string ascii){ // Initialize final String string hex = \"\"; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.length(); i++) { // Take a char from // position i of string char ch = ascii[i]; // Cast char to integer and // find its ascii value int tmp = (int)ch; // Change this ascii value // integer to hexadecimal value string part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex;}int main(){ // Driver code // Print the Hex String cout << (ASCIItoHEX(\"Geek\"));} // this code is contributed by phasing17", "e": 3137, "s": 1430, "text": null }, { "code": "// Java program to convert ASCII// string to Hexadecimal format stringimport java.util.Scanner; class ASCIItoHEX { // function to convert ASCII to HEX public static String ASCIItoHEX(String ascii) { // Initialize final String String hex = \"\"; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.length(); i++) { // take a char from // position i of string char ch = ascii.charAt(i); // cast char to integer and // find its ascii value int in = (int)ch; // change this ascii value // integer to hexadecimal value String part = Integer.toHexString(in); // add this hexadecimal value // to final string. hex += part; } // return the final string hex return hex; } // Driver Function public static void main(String arg[]) { // print the Hex String System.out.println(ASCIItoHEX(\"Geek\")); }}", "e": 4214, "s": 3137, "text": null }, { "code": "# Python3 program to convert ASCII# string to Hexadecimal format string # function to convert ASCII to HEXdef ASCIItoHEX(ascii): # Initialize final String hexa = \"\" # Make a loop to iterate through # every character of ascii string for i in range(len(ascii)): # take a char from # position i of string ch = ascii[i] # cast char to integer and # find its ascii value in1 = ord(ch) # change this ascii value # integer to hexadecimal value part = hex(in1).lstrip(\"0x\").rstrip(\"L\") # add this hexadecimal value # to final string. hexa += part # return the final string hex return hexa # Driver Functionif __name__ == '__main__': # print the Hex String print(ASCIItoHEX(\"Geek\")) # This code is contributed by pratham76", "e": 5051, "s": 4214, "text": null }, { "code": "// C# program to convert// ASCII string to Hexadecimal// format stringusing System;class GFG{ // Function to convert// decimal to hexadecimalstatic string decToHexa(int n){ // char array to store // hexadecimal number char []hexaDeciNum = new char[100]; // counter for hexadecimal // number array int i = 0; while(n != 0) { // temporary variable // to store remainder int temp = 0; // Storing remainder // in temp variable. temp = n % 16; // Check if temp < 10 if(temp < 10) { hexaDeciNum[i] = (char)(temp + 48); i++; } else { hexaDeciNum[i] = (char)(temp + 87); i++; } n = n / 16; } string ans = \"\"; // Printing hexadecimal number // array in reverse order for(int j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans;} // Function to convert ASCII to HEXpublic static string ASCIItoHEX(string ascii){ // Initialize final String string hex = \"\"; // Make a loop to iterate through // every character of ascii string for (int i = 0; i < ascii.Length; i++) { // Take a char from // position i of string char ch = ascii[i]; // Cast char to integer and // find its ascii value int tmp = (int)ch; // Change this ascii value // integer to hexadecimal value string part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex;} // Driver codepublic static void Main(string []arg){ // Print the Hex String Console.Write(ASCIItoHEX(\"Geek\"));}} // This code is contributed by rutvik_56", "e": 6713, "s": 5051, "text": null }, { "code": "<script> // JavaScript program to convert // ASCII string to Hexadecimal // format string // Function to convert // decimal to hexadecimal function decToHexa(n) { // char array to store // hexadecimal number var hexaDeciNum = new Array(100).fill(0); // counter for hexadecimal // number array var i = 0; while (n !== 0) { // temporary variable // to store remainder var temp = 0; // Storing remainder // in temp variable. temp = n % 16; // Check if temp < 10 if (temp < 10) { hexaDeciNum[i] = String.fromCharCode(temp + 48); i++; } else { hexaDeciNum[i] = String.fromCharCode(temp + 87); i++; } n = parseInt(n / 16); } var ans = \"\"; // Printing hexadecimal number // array in reverse order for (var j = i - 1; j >= 0; j--) { ans += hexaDeciNum[j]; } return ans; } // Function to convert ASCII to HEX function ASCIItoHEX(ascii) { // Initialize final String var hex = \"\"; // Make a loop to iterate through // every character of ascii string for (var i = 0; i < ascii.length; i++) { // Take a char from // position i of string var ch = ascii[i]; // Cast char to integer and // find its ascii value var tmp = ch.charCodeAt(0); // Change this ascii value // integer to hexadecimal value var part = decToHexa(tmp); // Add this hexadecimal value // to final string. hex += part; } // Return the final // string hex return hex; } // Driver code // Print the Hex String document.write(ASCIItoHEX(\"Geek\")); </script>", "e": 8624, "s": 6713, "text": null }, { "code": null, "e": 8634, "s": 8624, "text": "Output: " }, { "code": null, "e": 8643, "s": 8634, "text": "4765656b" }, { "code": null, "e": 8653, "s": 8643, "text": "rutvik_56" }, { "code": null, "e": 8663, "s": 8653, "text": "pratham76" }, { "code": null, "e": 8670, "s": 8663, "text": "rdtank" }, { "code": null, "e": 8680, "s": 8670, "text": "phasing17" }, { "code": null, "e": 8693, "s": 8680, "text": "Java-Strings" }, { "code": null, "e": 8707, "s": 8693, "text": "Java Programs" }, { "code": null, "e": 8715, "s": 8707, "text": "Strings" }, { "code": null, "e": 8728, "s": 8715, "text": "Java-Strings" }, { "code": null, "e": 8736, "s": 8728, "text": "Strings" }, { "code": null, "e": 8834, "s": 8736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8872, "s": 8834, "text": "Factory method design pattern in Java" }, { "code": null, "e": 8929, "s": 8872, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 8958, "s": 8929, "text": "Iterate through List in Java" }, { "code": null, "e": 9039, "s": 8958, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 9071, "s": 9039, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 9117, "s": 9071, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9142, "s": 9117, "text": "Reverse a string in Java" }, { "code": null, "e": 9202, "s": 9142, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9217, "s": 9202, "text": "C++ Data Types" } ]
Program to determine the Quadrant of a Complex number
19 May, 2021 Given a complex number in the form of the string str, the task is to determine the quadrant of the cartesian plane in which this complex number lies. Examples: Input: str = “1 + 1i” Output: Quadrant 1 Input: str = “0 + 0i” Output: Origin Approach: The idea is to first find the real and imaginary parts of a complex number. Let’s say the point is (x, iy), then the following table illustrates the position of the point with respect to the coordinates: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to determine the quadrant// of a complex number #include <bits/stdc++.h>using namespace std; // Function to determine the quadrant// of a complex numbervoid quadrant(string s){ int l = s.length(); int i; // Storing the index of '+' if (s.find('+') < l) { i = s.find('+'); } // Storing the index of '-' else { i = s.find('-'); } // Finding the real part // of the complex number string real = s.substr(0, i); // Finding the imaginary part // of the complex number string imaginary = s.substr(i + 1, l - 1); int x = stoi(real); int y = stoi(imaginary); if (x > 0 and y > 0) cout << "Quadrant 1"; else if (x < 0 and y > 0) cout << "Quadrant 2"; else if (x < 0 and y < 0) cout << "Quadrant 3"; else if (x > 0 and y < 0) cout << "Quadrant 4"; else if (x == 0 and y > 0) cout << "Lies on positive" << " Imaginary axis"; else if (x == 0 and y < 0) cout << "Lies on negative" << " Imaginary axis"; else if (y == 0 and x < 0) cout << "Lies on negative" << " X-axis"; else if (y == 0 and x > 0) cout << "Lies on positive" << " X-axis"; else cout << "Lies on the Origin";} // Driver codeint main(){ string s = "5+3i"; quadrant(s); return 0;} // Java program to determine the quadrant// of a complex numberimport java.util.*; class GFG{ // Function to determine the quadrant// of a complex numberstatic void quadrant(String s){ int l = s.length(); int i; // Storing the index of '+' if (s.contains("+")) { i = s.indexOf('+'); } // Storing the index of '-' else { i = s.indexOf('-'); } // Finding the real part // of the complex number String real = s.substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.substring(i + 1, l - 1); int x = Integer.valueOf(real); int y = Integer.valueOf(imaginary); if (x > 0 && y > 0) System.out.print("Quadrant 1"); else if (x < 0 && y > 0) System.out.print("Quadrant 2"); else if (x < 0 && y < 0) System.out.print("Quadrant 3"); else if (x > 0 && y < 0) System.out.print("Quadrant 4"); else if (x == 0 && y > 0) System.out.print("Lies on positive" + " Imaginary axis"); else if (x == 0 && y < 0) System.out.print("Lies on negative" + " Imaginary axis"); else if (y == 0 && x < 0) System.out.print("Lies on negative" + " X-axis"); else if (y == 0 && x > 0) System.out.print("Lies on positive" + " X-axis"); else System.out.print("Lies on the Origin");} // Driver codepublic static void main(String[] args){ String s = "5+3i"; quadrant(s);}} // This code is contributed by Rajput-Ji # Python 3 program to determine the quadrant# of a complex number # Function to determine the quadrant# of a complex numberdef quadrant(s): l = len(s) # Storing the index of '+' if ('+' in s): i = s.index('+') # Storing the index of '-' else: i = s.index('-') # Finding the real part # of the complex number real = s[0:i] # Finding the imaginary part # of the complex number imaginary = s[i + 1:l - 1] x = int(real) y = int(imaginary) if (x > 0 and y > 0): print("Quadrant 1") elif(x < 0 and y > 0): print("Quadrant 2") elif (x < 0 and y < 0): print("Quadrant 3") elif (x > 0 and y < 0): print("Quadrant 4") elif (x == 0 and y > 0): print("Lies on positive","Imaginary axis") elif (x == 0 and y < 0): print("Lies on negative","Imaginary axis") elif (y == 0 and x < 0): print("Lies on negative","X-axis") elif (y == 0 and x > 0): print("Lies on positive","X-axis") else: print("Lies on the Origin") # Driver codeif __name__ == '__main__': s = "5+3i" quadrant(s) # This code is contributed by Surendra_Gangwar // C# program to determine the quadrant// of a complex numberusing System; class GFG{ // Function to determine the quadrant// of a complex numberstatic void quadrant(String s){ int l = s.Length; int i; // Storing the index of '+' if (s.Contains("+")) { i = s.IndexOf('+'); } // Storing the index of '-' else { i = s.IndexOf('-'); } // Finding the real part // of the complex number String real = s.Substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.Substring(i + 1, l - 2 - i); int x = Int32.Parse(real); int y = Int32.Parse(imaginary); if (x > 0 && y > 0) Console.Write("Quadrant 1"); else if (x < 0 && y > 0) Console.Write("Quadrant 2"); else if (x < 0 && y < 0) Console.Write("Quadrant 3"); else if (x > 0 && y < 0) Console.Write("Quadrant 4"); else if (x == 0 && y > 0) Console.Write("Lies on positive" + " Imaginary axis"); else if (x == 0 && y < 0) Console.Write("Lies on negative" + " Imaginary axis"); else if (y == 0 && x < 0) Console.Write("Lies on negative" + " X-axis"); else if (y == 0 && x > 0) Console.Write("Lies on positive" + " X-axis"); else Console.Write("Lies on the Origin");} // Driver codepublic static void Main(String[] args){ String s = "5+3i"; quadrant(s);}} // This code is contributed by sapnasingh4991 <script>// Javascript program // Function to determine the quadrant// of a complex numberfunction quadrant(s){ var l = s.length; var i =0 ; // Storing the index of '+' if (s.indexOf("+") != -1) { i = s.indexOf("+"); } // Storing the index of '-' else { i = s.indexOf("-"); } // Finding the real part // of the complex number var real = s.substr(0, i); // Finding the imaginary part // of the complex number var imaginary = s.substr(i + 1, l - 1); var x = parseInt(real); var y = parseInt(imaginary); if (x > 0 && y > 0) document.write("Quadrant 1"); else if (x < 0 && y > 0) document.write("Quadrant 2"); else if (x < 0 && y < 0) document.write( "Quadrant 3"); else if (x > 0 && y < 0) document.write( "Quadrant 4"); else if (x == 0 && y > 0) document.write( "Lies on positive"+" Imaginary axis"); else if (x == 0 && y < 0) document.write( "Lies on negative"+" Imaginary axis"); else if (y == 0 && x < 0) document.write( "Lies on negative"+" X-axis"); else if (y == 0 && x > 0) document.write( "Lies on positive"+" X-axis"); else document.write( "Lies on the Origin");} var s = "5+3i";quadrant(s);</script> Quadrant 1 SURENDRA_GANGWAR Rajput-Ji sapnasingh4991 shivanisinghss2110 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2021" }, { "code": null, "e": 178, "s": 28, "text": "Given a complex number in the form of the string str, the task is to determine the quadrant of the cartesian plane in which this complex number lies." }, { "code": null, "e": 189, "s": 178, "text": "Examples: " }, { "code": null, "e": 230, "s": 189, "text": "Input: str = “1 + 1i” Output: Quadrant 1" }, { "code": null, "e": 267, "s": 230, "text": "Input: str = “0 + 0i” Output: Origin" }, { "code": null, "e": 277, "s": 267, "text": "Approach:" }, { "code": null, "e": 482, "s": 277, "text": "The idea is to first find the real and imaginary parts of a complex number. Let’s say the point is (x, iy), then the following table illustrates the position of the point with respect to the coordinates: " }, { "code": null, "e": 534, "s": 482, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 538, "s": 534, "text": "C++" }, { "code": null, "e": 543, "s": 538, "text": "Java" }, { "code": null, "e": 551, "s": 543, "text": "Python3" }, { "code": null, "e": 554, "s": 551, "text": "C#" }, { "code": null, "e": 565, "s": 554, "text": "Javascript" }, { "code": "// C++ program to determine the quadrant// of a complex number #include <bits/stdc++.h>using namespace std; // Function to determine the quadrant// of a complex numbervoid quadrant(string s){ int l = s.length(); int i; // Storing the index of '+' if (s.find('+') < l) { i = s.find('+'); } // Storing the index of '-' else { i = s.find('-'); } // Finding the real part // of the complex number string real = s.substr(0, i); // Finding the imaginary part // of the complex number string imaginary = s.substr(i + 1, l - 1); int x = stoi(real); int y = stoi(imaginary); if (x > 0 and y > 0) cout << \"Quadrant 1\"; else if (x < 0 and y > 0) cout << \"Quadrant 2\"; else if (x < 0 and y < 0) cout << \"Quadrant 3\"; else if (x > 0 and y < 0) cout << \"Quadrant 4\"; else if (x == 0 and y > 0) cout << \"Lies on positive\" << \" Imaginary axis\"; else if (x == 0 and y < 0) cout << \"Lies on negative\" << \" Imaginary axis\"; else if (y == 0 and x < 0) cout << \"Lies on negative\" << \" X-axis\"; else if (y == 0 and x > 0) cout << \"Lies on positive\" << \" X-axis\"; else cout << \"Lies on the Origin\";} // Driver codeint main(){ string s = \"5+3i\"; quadrant(s); return 0;}", "e": 1934, "s": 565, "text": null }, { "code": "// Java program to determine the quadrant// of a complex numberimport java.util.*; class GFG{ // Function to determine the quadrant// of a complex numberstatic void quadrant(String s){ int l = s.length(); int i; // Storing the index of '+' if (s.contains(\"+\")) { i = s.indexOf('+'); } // Storing the index of '-' else { i = s.indexOf('-'); } // Finding the real part // of the complex number String real = s.substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.substring(i + 1, l - 1); int x = Integer.valueOf(real); int y = Integer.valueOf(imaginary); if (x > 0 && y > 0) System.out.print(\"Quadrant 1\"); else if (x < 0 && y > 0) System.out.print(\"Quadrant 2\"); else if (x < 0 && y < 0) System.out.print(\"Quadrant 3\"); else if (x > 0 && y < 0) System.out.print(\"Quadrant 4\"); else if (x == 0 && y > 0) System.out.print(\"Lies on positive\" + \" Imaginary axis\"); else if (x == 0 && y < 0) System.out.print(\"Lies on negative\" + \" Imaginary axis\"); else if (y == 0 && x < 0) System.out.print(\"Lies on negative\" + \" X-axis\"); else if (y == 0 && x > 0) System.out.print(\"Lies on positive\" + \" X-axis\"); else System.out.print(\"Lies on the Origin\");} // Driver codepublic static void main(String[] args){ String s = \"5+3i\"; quadrant(s);}} // This code is contributed by Rajput-Ji", "e": 3477, "s": 1934, "text": null }, { "code": "# Python 3 program to determine the quadrant# of a complex number # Function to determine the quadrant# of a complex numberdef quadrant(s): l = len(s) # Storing the index of '+' if ('+' in s): i = s.index('+') # Storing the index of '-' else: i = s.index('-') # Finding the real part # of the complex number real = s[0:i] # Finding the imaginary part # of the complex number imaginary = s[i + 1:l - 1] x = int(real) y = int(imaginary) if (x > 0 and y > 0): print(\"Quadrant 1\") elif(x < 0 and y > 0): print(\"Quadrant 2\") elif (x < 0 and y < 0): print(\"Quadrant 3\") elif (x > 0 and y < 0): print(\"Quadrant 4\") elif (x == 0 and y > 0): print(\"Lies on positive\",\"Imaginary axis\") elif (x == 0 and y < 0): print(\"Lies on negative\",\"Imaginary axis\") elif (y == 0 and x < 0): print(\"Lies on negative\",\"X-axis\") elif (y == 0 and x > 0): print(\"Lies on positive\",\"X-axis\") else: print(\"Lies on the Origin\") # Driver codeif __name__ == '__main__': s = \"5+3i\" quadrant(s) # This code is contributed by Surendra_Gangwar", "e": 4651, "s": 3477, "text": null }, { "code": "// C# program to determine the quadrant// of a complex numberusing System; class GFG{ // Function to determine the quadrant// of a complex numberstatic void quadrant(String s){ int l = s.Length; int i; // Storing the index of '+' if (s.Contains(\"+\")) { i = s.IndexOf('+'); } // Storing the index of '-' else { i = s.IndexOf('-'); } // Finding the real part // of the complex number String real = s.Substring(0, i); // Finding the imaginary part // of the complex number String imaginary = s.Substring(i + 1, l - 2 - i); int x = Int32.Parse(real); int y = Int32.Parse(imaginary); if (x > 0 && y > 0) Console.Write(\"Quadrant 1\"); else if (x < 0 && y > 0) Console.Write(\"Quadrant 2\"); else if (x < 0 && y < 0) Console.Write(\"Quadrant 3\"); else if (x > 0 && y < 0) Console.Write(\"Quadrant 4\"); else if (x == 0 && y > 0) Console.Write(\"Lies on positive\" + \" Imaginary axis\"); else if (x == 0 && y < 0) Console.Write(\"Lies on negative\" + \" Imaginary axis\"); else if (y == 0 && x < 0) Console.Write(\"Lies on negative\" + \" X-axis\"); else if (y == 0 && x > 0) Console.Write(\"Lies on positive\" + \" X-axis\"); else Console.Write(\"Lies on the Origin\");} // Driver codepublic static void Main(String[] args){ String s = \"5+3i\"; quadrant(s);}} // This code is contributed by sapnasingh4991", "e": 6175, "s": 4651, "text": null }, { "code": "<script>// Javascript program // Function to determine the quadrant// of a complex numberfunction quadrant(s){ var l = s.length; var i =0 ; // Storing the index of '+' if (s.indexOf(\"+\") != -1) { i = s.indexOf(\"+\"); } // Storing the index of '-' else { i = s.indexOf(\"-\"); } // Finding the real part // of the complex number var real = s.substr(0, i); // Finding the imaginary part // of the complex number var imaginary = s.substr(i + 1, l - 1); var x = parseInt(real); var y = parseInt(imaginary); if (x > 0 && y > 0) document.write(\"Quadrant 1\"); else if (x < 0 && y > 0) document.write(\"Quadrant 2\"); else if (x < 0 && y < 0) document.write( \"Quadrant 3\"); else if (x > 0 && y < 0) document.write( \"Quadrant 4\"); else if (x == 0 && y > 0) document.write( \"Lies on positive\"+\" Imaginary axis\"); else if (x == 0 && y < 0) document.write( \"Lies on negative\"+\" Imaginary axis\"); else if (y == 0 && x < 0) document.write( \"Lies on negative\"+\" X-axis\"); else if (y == 0 && x > 0) document.write( \"Lies on positive\"+\" X-axis\"); else document.write( \"Lies on the Origin\");} var s = \"5+3i\";quadrant(s);</script>", "e": 7486, "s": 6175, "text": null }, { "code": null, "e": 7497, "s": 7486, "text": "Quadrant 1" }, { "code": null, "e": 7516, "s": 7499, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 7526, "s": 7516, "text": "Rajput-Ji" }, { "code": null, "e": 7541, "s": 7526, "text": "sapnasingh4991" }, { "code": null, "e": 7560, "s": 7541, "text": "shivanisinghss2110" }, { "code": null, "e": 7573, "s": 7560, "text": "Mathematical" }, { "code": null, "e": 7586, "s": 7573, "text": "Mathematical" } ]
Spring Boot – Integrating Hibernate and JPA
03 Jan, 2022 Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article we learn: What are JPA and Hibernate? How does JPA Work? How to integrate the SpringBoot project with Hibernate and JPA. JPA(Java Persistence API): JPA is like a bridge between the Spring application Models and the relational database that is used for managing and accessing the data between the Object-Oriented models of the Spring application and the database. In simple terms, we have to define all methods for inserting the records in the MySQL table if we don’t use the JPA. JPA doesn’t perform any kind of specific operations it provides various types of methods without implementation, just like an interface that contains various methods like counting the records, deleting the specific record. etc. Hibernate is a java framework and ORM (Object Relation Mapping) tool that is used to provide the implementation of the JPA methods. How does JPA Work? JPA is an abstraction that is used to map the java object with the database. It contains different structures of the methods that are used for manipulating the table record and also provides the SQL queries for specific operations. How to Integrate the SpringBoot project with Hibernate and JPA Step By Step Implementation Go to Spring InitializrFill in the details as per the requirementsClick on Generate which will download the starter projectExtract the zip file Go to Spring Initializr Fill in the details as per the requirements Click on Generate which will download the starter project Extract the zip file Create a project using the spring initializer. pom.xml file: XML <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>SpringBootApp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBootApp</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Extract the zip file. Now open a suitable IDE and then go to File -> New -> Project from existing sources -> Springbootapp and select pom.xml. Click on import changes on prompt and wait for the project to sync. Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project. For database operation we have to configure the Spring application with the database also it is required to add configuration of the database before executing the Spring project. If we try to run the Spring application that contains JPA dependency with adding the configuration of the database it causes an error. Running the project without database configuration: Run the SpringBootAppApplication: Configuring the Spring application with the database: application.properties file: spring.datasource.url=jdbc:mysql://localhost:3306/user spring.datasource.username=root spring.datasource.password=Aayush spring.jpa.hibernate.ddl-auto=update Now run the Spring Boot application after configuration these properties: Java-Spring-Boot Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jan, 2022" }, { "code": null, "e": 451, "s": 28, "text": "Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time." }, { "code": null, "e": 477, "s": 451, "text": "In this article we learn:" }, { "code": null, "e": 505, "s": 477, "text": "What are JPA and Hibernate?" }, { "code": null, "e": 524, "s": 505, "text": "How does JPA Work?" }, { "code": null, "e": 588, "s": 524, "text": "How to integrate the SpringBoot project with Hibernate and JPA." }, { "code": null, "e": 1175, "s": 588, "text": "JPA(Java Persistence API): JPA is like a bridge between the Spring application Models and the relational database that is used for managing and accessing the data between the Object-Oriented models of the Spring application and the database. In simple terms, we have to define all methods for inserting the records in the MySQL table if we don’t use the JPA. JPA doesn’t perform any kind of specific operations it provides various types of methods without implementation, just like an interface that contains various methods like counting the records, deleting the specific record. etc." }, { "code": null, "e": 1308, "s": 1175, "text": "Hibernate is a java framework and ORM (Object Relation Mapping) tool that is used to provide the implementation of the JPA methods." }, { "code": null, "e": 1327, "s": 1308, "text": "How does JPA Work?" }, { "code": null, "e": 1559, "s": 1327, "text": "JPA is an abstraction that is used to map the java object with the database. It contains different structures of the methods that are used for manipulating the table record and also provides the SQL queries for specific operations." }, { "code": null, "e": 1622, "s": 1559, "text": "How to Integrate the SpringBoot project with Hibernate and JPA" }, { "code": null, "e": 1650, "s": 1622, "text": "Step By Step Implementation" }, { "code": null, "e": 1794, "s": 1650, "text": "Go to Spring InitializrFill in the details as per the requirementsClick on Generate which will download the starter projectExtract the zip file" }, { "code": null, "e": 1818, "s": 1794, "text": "Go to Spring Initializr" }, { "code": null, "e": 1862, "s": 1818, "text": "Fill in the details as per the requirements" }, { "code": null, "e": 1920, "s": 1862, "text": "Click on Generate which will download the starter project" }, { "code": null, "e": 1941, "s": 1920, "text": "Extract the zip file" }, { "code": null, "e": 1988, "s": 1941, "text": "Create a project using the spring initializer." }, { "code": null, "e": 2002, "s": 1988, "text": "pom.xml file:" }, { "code": null, "e": 2006, "s": 2002, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>SpringBootApp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBootApp</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>", "e": 3743, "s": 2006, "text": null }, { "code": null, "e": 3954, "s": 3743, "text": "Extract the zip file. Now open a suitable IDE and then go to File -> New -> Project from existing sources -> Springbootapp and select pom.xml. Click on import changes on prompt and wait for the project to sync." }, { "code": null, "e": 4092, "s": 3954, "text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project." }, { "code": null, "e": 4458, "s": 4092, "text": "For database operation we have to configure the Spring application with the database also it is required to add configuration of the database before executing the Spring project. If we try to run the Spring application that contains JPA dependency with adding the configuration of the database it causes an error. Running the project without database configuration:" }, { "code": null, "e": 4492, "s": 4458, "text": "Run the SpringBootAppApplication:" }, { "code": null, "e": 4546, "s": 4492, "text": "Configuring the Spring application with the database:" }, { "code": null, "e": 4575, "s": 4546, "text": "application.properties file:" }, { "code": null, "e": 4734, "s": 4575, "text": "spring.datasource.url=jdbc:mysql://localhost:3306/user\nspring.datasource.username=root\nspring.datasource.password=Aayush\nspring.jpa.hibernate.ddl-auto=update " }, { "code": null, "e": 4810, "s": 4734, "text": " Now run the Spring Boot application after configuration these properties: " }, { "code": null, "e": 4827, "s": 4810, "text": "Java-Spring-Boot" }, { "code": null, "e": 4832, "s": 4827, "text": "Java" }, { "code": null, "e": 4837, "s": 4832, "text": "Java" }, { "code": null, "e": 4935, "s": 4837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4950, "s": 4935, "text": "Stream In Java" }, { "code": null, "e": 4971, "s": 4950, "text": "Introduction to Java" }, { "code": null, "e": 4992, "s": 4971, "text": "Constructors in Java" }, { "code": null, "e": 5011, "s": 4992, "text": "Exceptions in Java" }, { "code": null, "e": 5028, "s": 5011, "text": "Generics in Java" }, { "code": null, "e": 5058, "s": 5028, "text": "Functional Interfaces in Java" }, { "code": null, "e": 5084, "s": 5058, "text": "Java Programming Examples" }, { "code": null, "e": 5100, "s": 5084, "text": "Strings in Java" }, { "code": null, "e": 5137, "s": 5100, "text": "Differences between JDK, JRE and JVM" } ]
Semantic Analysis in Compiler Design
22 Apr, 2020 Semantic Analysis is the third phase of Compiler. Semantic Analysis makes sure that declarations and statements of program are semantically correct. It is a collection of procedures which is called by parser as and when required by grammar. Both syntax tree of previous phase and symbol table are used to check the consistency of the given code. Type checking is an important part of semantic analysis where compiler makes sure that each operator has matching operands. Semantic Analyzer:It uses syntax tree and symbol table to check whether the given program is semantically consistent with language definition. It gathers type information and stores it in either syntax tree or symbol table. This type information is subsequently used by compiler during intermediate-code generation. Semantic Errors:Errors recognized by semantic analyzer are as follows: Type mismatch Undeclared variables Reserved identifier misuse Functions of Semantic Analysis: Type Checking –Ensures that data types are used in a way consistent with their definition.Label Checking –A program should contain labels references.Flow Control Check –Keeps a check that control structures are used in a proper manner.(example: no break statement outside a loop) Type Checking –Ensures that data types are used in a way consistent with their definition. Label Checking –A program should contain labels references. Flow Control Check –Keeps a check that control structures are used in a proper manner.(example: no break statement outside a loop) Example: float x = 10.1; float y = x*30; In the above example integer 30 will be typecasted to float 30.0 before multiplication, by semantic analyzer. Static and Dynamic Semantics: Static Semantics –It is named so because of the fact that these are checked at compile time. The static semantics and meaning of program during execution, are indirectly related.Dynamic Semantic Analysis –It defines the meaning of different units of program like expressions and statements. These are checked at runtime unlike static semantics. Static Semantics –It is named so because of the fact that these are checked at compile time. The static semantics and meaning of program during execution, are indirectly related. Dynamic Semantic Analysis –It defines the meaning of different units of program like expressions and statements. These are checked at runtime unlike static semantics. sachiniyermalkapur Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2020" }, { "code": null, "e": 522, "s": 52, "text": "Semantic Analysis is the third phase of Compiler. Semantic Analysis makes sure that declarations and statements of program are semantically correct. It is a collection of procedures which is called by parser as and when required by grammar. Both syntax tree of previous phase and symbol table are used to check the consistency of the given code. Type checking is an important part of semantic analysis where compiler makes sure that each operator has matching operands." }, { "code": null, "e": 838, "s": 522, "text": "Semantic Analyzer:It uses syntax tree and symbol table to check whether the given program is semantically consistent with language definition. It gathers type information and stores it in either syntax tree or symbol table. This type information is subsequently used by compiler during intermediate-code generation." }, { "code": null, "e": 909, "s": 838, "text": "Semantic Errors:Errors recognized by semantic analyzer are as follows:" }, { "code": null, "e": 923, "s": 909, "text": "Type mismatch" }, { "code": null, "e": 944, "s": 923, "text": "Undeclared variables" }, { "code": null, "e": 971, "s": 944, "text": "Reserved identifier misuse" }, { "code": null, "e": 1003, "s": 971, "text": "Functions of Semantic Analysis:" }, { "code": null, "e": 1283, "s": 1003, "text": "Type Checking –Ensures that data types are used in a way consistent with their definition.Label Checking –A program should contain labels references.Flow Control Check –Keeps a check that control structures are used in a proper manner.(example: no break statement outside a loop)" }, { "code": null, "e": 1374, "s": 1283, "text": "Type Checking –Ensures that data types are used in a way consistent with their definition." }, { "code": null, "e": 1434, "s": 1374, "text": "Label Checking –A program should contain labels references." }, { "code": null, "e": 1565, "s": 1434, "text": "Flow Control Check –Keeps a check that control structures are used in a proper manner.(example: no break statement outside a loop)" }, { "code": null, "e": 1574, "s": 1565, "text": "Example:" }, { "code": null, "e": 1607, "s": 1574, "text": "float x = 10.1;\nfloat y = x*30; " }, { "code": null, "e": 1717, "s": 1607, "text": "In the above example integer 30 will be typecasted to float 30.0 before multiplication, by semantic analyzer." }, { "code": null, "e": 1747, "s": 1717, "text": "Static and Dynamic Semantics:" }, { "code": null, "e": 2092, "s": 1747, "text": "Static Semantics –It is named so because of the fact that these are checked at compile time. The static semantics and meaning of program during execution, are indirectly related.Dynamic Semantic Analysis –It defines the meaning of different units of program like expressions and statements. These are checked at runtime unlike static semantics." }, { "code": null, "e": 2271, "s": 2092, "text": "Static Semantics –It is named so because of the fact that these are checked at compile time. The static semantics and meaning of program during execution, are indirectly related." }, { "code": null, "e": 2438, "s": 2271, "text": "Dynamic Semantic Analysis –It defines the meaning of different units of program like expressions and statements. These are checked at runtime unlike static semantics." }, { "code": null, "e": 2457, "s": 2438, "text": "sachiniyermalkapur" }, { "code": null, "e": 2473, "s": 2457, "text": "Compiler Design" }, { "code": null, "e": 2481, "s": 2473, "text": "GATE CS" }, { "code": null, "e": 2579, "s": 2481, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2637, "s": 2579, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 2670, "s": 2637, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 2701, "s": 2670, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 2771, "s": 2701, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 2811, "s": 2771, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 2831, "s": 2811, "text": "Layers of OSI Model" }, { "code": null, "e": 2855, "s": 2831, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2868, "s": 2855, "text": "TCP/IP Model" }, { "code": null, "e": 2895, "s": 2868, "text": "Types of Operating Systems" } ]
JavaScript | Let
06 Jun, 2022 let is a keyword used to declare variables in JavaScript that are block scoped. There are three ways you can declare variables in JavaScript let, const, var(old). Like other keywords, let keyword could be easily used inside or outside a function as per user requirement. ES6 or ES2015 defines new keywords to declare variables in JavaScript. Generally, it is suggested that we must use the let keyword while working on any major or large-scale project. Even in a small project also, it makes a habit of an individual if let keyword is implemented while variable declaration. Syntax: Following syntax we may use to declare using let keyword: let variable_name = value; Block Scope: A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. Global Scope: javascript let num=10;console.log(num);function fun(){ console.log(num);}fun(); // calling the function Output: Function Scope: javascript function fun(){ let num=10; console.log(num);}fun(); // calling the functionconsole.log(num); Output: Block Scope: javascript { let x=23; console.log(x);}console.log(x); Output: Redeclaring Variables in different blocks: javascript let x=77;{ let x=23; console.log(x);}console.log(x); Output: Redeclaring Variables in same blocks: javascript let x=77;{ let x=23; // legal console.log(x);}let x=67;// illegalconsole.log(x); Output: Does not support Hoisting: javascript x=12;console.log(x);let x; Output: Supported Browser: Chrome 49 and above Edge 14 and above Firefox 44 and above Opera 17 and above Internet Explorer 11 and above Safari 10 and above arorakashish0911 ysachin2314 amansingla technophpfij javascript-basics Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? How to calculate the number of days between two dates in javascript? File uploading in React.js Roadmap to Learn JavaScript For Beginners
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jun, 2022" }, { "code": null, "e": 629, "s": 53, "text": "let is a keyword used to declare variables in JavaScript that are block scoped. There are three ways you can declare variables in JavaScript let, const, var(old). Like other keywords, let keyword could be easily used inside or outside a function as per user requirement. ES6 or ES2015 defines new keywords to declare variables in JavaScript. Generally, it is suggested that we must use the let keyword while working on any major or large-scale project. Even in a small project also, it makes a habit of an individual if let keyword is implemented while variable declaration. " }, { "code": null, "e": 637, "s": 629, "text": "Syntax:" }, { "code": null, "e": 695, "s": 637, "text": "Following syntax we may use to declare using let keyword:" }, { "code": null, "e": 722, "s": 695, "text": "let variable_name = value;" }, { "code": null, "e": 737, "s": 724, "text": "Block Scope:" }, { "code": null, "e": 972, "s": 737, "text": "A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. " }, { "code": null, "e": 986, "s": 972, "text": "Global Scope:" }, { "code": null, "e": 999, "s": 988, "text": "javascript" }, { "code": "let num=10;console.log(num);function fun(){ console.log(num);}fun(); // calling the function", "e": 1095, "s": 999, "text": null }, { "code": null, "e": 1105, "s": 1095, "text": "Output: " }, { "code": null, "e": 1123, "s": 1107, "text": "Function Scope:" }, { "code": null, "e": 1136, "s": 1125, "text": "javascript" }, { "code": "function fun(){ let num=10; console.log(num);}fun(); // calling the functionconsole.log(num);", "e": 1237, "s": 1136, "text": null }, { "code": null, "e": 1247, "s": 1237, "text": "Output: " }, { "code": null, "e": 1262, "s": 1249, "text": "Block Scope:" }, { "code": null, "e": 1275, "s": 1264, "text": "javascript" }, { "code": "{ let x=23; console.log(x);}console.log(x);", "e": 1325, "s": 1275, "text": null }, { "code": null, "e": 1335, "s": 1325, "text": "Output: " }, { "code": null, "e": 1380, "s": 1337, "text": "Redeclaring Variables in different blocks:" }, { "code": null, "e": 1393, "s": 1382, "text": "javascript" }, { "code": "let x=77;{ let x=23; console.log(x);}console.log(x);", "e": 1452, "s": 1393, "text": null }, { "code": null, "e": 1462, "s": 1452, "text": "Output: " }, { "code": null, "e": 1502, "s": 1464, "text": "Redeclaring Variables in same blocks:" }, { "code": null, "e": 1515, "s": 1504, "text": "javascript" }, { "code": "let x=77;{ let x=23; // legal console.log(x);}let x=67;// illegalconsole.log(x);", "e": 1602, "s": 1515, "text": null }, { "code": null, "e": 1612, "s": 1602, "text": "Output: " }, { "code": null, "e": 1643, "s": 1616, "text": "Does not support Hoisting:" }, { "code": null, "e": 1656, "s": 1645, "text": "javascript" }, { "code": "x=12;console.log(x);let x;", "e": 1683, "s": 1656, "text": null }, { "code": null, "e": 1693, "s": 1683, "text": "Output: " }, { "code": null, "e": 1713, "s": 1693, "text": " Supported Browser:" }, { "code": null, "e": 1733, "s": 1713, "text": "Chrome 49 and above" }, { "code": null, "e": 1751, "s": 1733, "text": "Edge 14 and above" }, { "code": null, "e": 1772, "s": 1751, "text": "Firefox 44 and above" }, { "code": null, "e": 1791, "s": 1772, "text": "Opera 17 and above" }, { "code": null, "e": 1822, "s": 1791, "text": "Internet Explorer 11 and above" }, { "code": null, "e": 1842, "s": 1822, "text": "Safari 10 and above" }, { "code": null, "e": 1859, "s": 1842, "text": "arorakashish0911" }, { "code": null, "e": 1871, "s": 1859, "text": "ysachin2314" }, { "code": null, "e": 1882, "s": 1871, "text": "amansingla" }, { "code": null, "e": 1895, "s": 1882, "text": "technophpfij" }, { "code": null, "e": 1913, "s": 1895, "text": "javascript-basics" }, { "code": null, "e": 1920, "s": 1913, "text": "Picked" }, { "code": null, "e": 1931, "s": 1920, "text": "JavaScript" }, { "code": null, "e": 2029, "s": 1931, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2090, "s": 2029, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2162, "s": 2090, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2202, "s": 2162, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2255, "s": 2202, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2307, "s": 2255, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2348, "s": 2307, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2394, "s": 2348, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 2463, "s": 2394, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 2490, "s": 2463, "text": "File uploading in React.js" } ]
JavaScript | Pad a number with leading zeros
20 May, 2019 The String prototype property is used to pad a number with leading zeros. This property allows for adding new properties and methods to existing object types. Syntax: object.prototype.name = value Return value: It returns a reference to the String.prototype object. Example 1: This example adds leading zeros to a number by creating a function and inside this function, if the number is less than the width provided then it adds the leading zeros. <!DOCTYPE html> <html> <head> <title> JavaScript | Pad a number with leading zeros </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px;"></p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var num = 2213; el_up.innerHTML = 'Number = ' +num; function pad(n, width) { n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n; } function gfg_Run() { el_down.innerHTML = pad(num, 7); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds leading zeros to a number by creating a prototype pad. In this example we can pass a string to the object, whatever we want to pad with the number. <!DOCTYPE html> <html> <head> <title> JavaScript | Pad a number with leading zeros </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 16px;"></p> <button onclick = "gfg_Run()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var num = '29213'; el_up.innerHTML = 'Number = ' + num; String.prototype.pad = function(String, len) { var str = this; while (str.length < len) str = String + str; return str; } function gfg_Run() { el_down.innerHTML = num.pad("0", 9); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 187, "s": 28, "text": "The String prototype property is used to pad a number with leading zeros. This property allows for adding new properties and methods to existing object types." }, { "code": null, "e": 195, "s": 187, "text": "Syntax:" }, { "code": null, "e": 225, "s": 195, "text": "object.prototype.name = value" }, { "code": null, "e": 294, "s": 225, "text": "Return value: It returns a reference to the String.prototype object." }, { "code": null, "e": 476, "s": 294, "text": "Example 1: This example adds leading zeros to a number by creating a function and inside this function, if the number is less than the width provided then it adds the leading zeros." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Pad a number with leading zeros </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px;\"></p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var num = 2213; el_up.innerHTML = 'Number = ' +num; function pad(n, width) { n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n; } function gfg_Run() { el_down.innerHTML = pad(num, 7); } </script> </body> </html> ", "e": 1603, "s": 476, "text": null }, { "code": null, "e": 1611, "s": 1603, "text": "Output:" }, { "code": null, "e": 1642, "s": 1611, "text": "Before clicking on the button:" }, { "code": null, "e": 1672, "s": 1642, "text": "After clicking on the button:" }, { "code": null, "e": 1849, "s": 1672, "text": "Example 2: This example adds leading zeros to a number by creating a prototype pad. In this example we can pass a string to the object, whatever we want to pad with the number." }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript | Pad a number with leading zeros </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 16px;\"></p> <button onclick = \"gfg_Run()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var num = '29213'; el_up.innerHTML = 'Number = ' + num; String.prototype.pad = function(String, len) { var str = this; while (str.length < len) str = String + str; return str; } function gfg_Run() { el_down.innerHTML = num.pad(\"0\", 9); } </script> </body> </html> ", "e": 3022, "s": 1849, "text": null }, { "code": null, "e": 3030, "s": 3022, "text": "Output:" }, { "code": null, "e": 3061, "s": 3030, "text": "Before clicking on the button:" }, { "code": null, "e": 3091, "s": 3061, "text": "After clicking on the button:" }, { "code": null, "e": 3107, "s": 3091, "text": "JavaScript-Misc" }, { "code": null, "e": 3118, "s": 3107, "text": "JavaScript" }, { "code": null, "e": 3135, "s": 3118, "text": "Web Technologies" }, { "code": null, "e": 3162, "s": 3135, "text": "Web technologies Questions" }, { "code": null, "e": 3260, "s": 3162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3321, "s": 3260, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3393, "s": 3321, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3433, "s": 3393, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3474, "s": 3433, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3516, "s": 3474, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3549, "s": 3516, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3611, "s": 3549, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3672, "s": 3611, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3722, "s": 3672, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference Between Imperative and Declarative Programming
07 Jul, 2021 A programming paradigm is an approach to solve problems using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming languages, there are lots of paradigms to fulfill each and every demand. Programming Paradigms Imperative Programming as the name suggests is a type of programming paradigm that describes how the program executes. Developers are more concerned with how to get an answer step by step. It comprises the sequence of command imperatives. In this, the order of execution is very important and uses both mutable and immutable data. Fortran, Java, C, C++ programming languages are examples of imperative programming. Declarative Programming as the name suggests is a type of programming paradigm that describes what programs to be executed. Developers are more concerned with the answer that is received. It declares what kind of results we want and leave programming language aside focusing on simply figuring out how to produce them. In simple words, it mainly focuses on end result. It expresses the logic of computation. Miranda, Erlang, Haskell, Prolog are a few popular examples of declarative programming. After getting the basics of understanding of both the languages now let u do discuss the key differences between these two different types of programming Imperative Programming Declarative Programming jacob341 Functions logical-thinking Difference Between Programming Language logical-thinking Functions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Process and Thread Difference between Clustered and Non-clustered index Differences between IPv4 and IPv6 Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Decorators with parameters in Python C# | Data Types
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2021" }, { "code": null, "e": 551, "s": 54, "text": "A programming paradigm is an approach to solve problems using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots of programming languages that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming languages, there are lots of paradigms to fulfill each and every demand." }, { "code": null, "e": 573, "s": 551, "text": "Programming Paradigms" }, { "code": null, "e": 989, "s": 573, "text": "Imperative Programming as the name suggests is a type of programming paradigm that describes how the program executes. Developers are more concerned with how to get an answer step by step. It comprises the sequence of command imperatives. In this, the order of execution is very important and uses both mutable and immutable data. Fortran, Java, C, C++ programming languages are examples of imperative programming. " }, { "code": null, "e": 1485, "s": 989, "text": "Declarative Programming as the name suggests is a type of programming paradigm that describes what programs to be executed. Developers are more concerned with the answer that is received. It declares what kind of results we want and leave programming language aside focusing on simply figuring out how to produce them. In simple words, it mainly focuses on end result. It expresses the logic of computation. Miranda, Erlang, Haskell, Prolog are a few popular examples of declarative programming." }, { "code": null, "e": 1639, "s": 1485, "text": "After getting the basics of understanding of both the languages now let u do discuss the key differences between these two different types of programming" }, { "code": null, "e": 1662, "s": 1639, "text": "Imperative Programming" }, { "code": null, "e": 1688, "s": 1662, "text": "Declarative Programming " }, { "code": null, "e": 1697, "s": 1688, "text": "jacob341" }, { "code": null, "e": 1707, "s": 1697, "text": "Functions" }, { "code": null, "e": 1724, "s": 1707, "text": "logical-thinking" }, { "code": null, "e": 1743, "s": 1724, "text": "Difference Between" }, { "code": null, "e": 1764, "s": 1743, "text": "Programming Language" }, { "code": null, "e": 1781, "s": 1764, "text": "logical-thinking" }, { "code": null, "e": 1791, "s": 1781, "text": "Functions" }, { "code": null, "e": 1889, "s": 1791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1950, "s": 1889, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2018, "s": 1950, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 2056, "s": 2018, "text": "Difference between Process and Thread" }, { "code": null, "e": 2109, "s": 2056, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2143, "s": 2109, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2184, "s": 2143, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 2227, "s": 2184, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 2245, "s": 2227, "text": "Structures in C++" }, { "code": null, "e": 2282, "s": 2245, "text": "Decorators with parameters in Python" } ]
C | Advanced Pointer | Question 1 - GeeksforGeeks
28 Jun, 2021 void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf("%d", *p); return 0; } (A) 10(B) 20(C) Compiler error(D) Runtime ErrorAnswer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local pointer of one function inside another function, then we must pass pointer to the pointer. By passing the pointer to the pointer, we can change pointer to point to something else. See the following program as an example. void fun(int **pptr) { static int q = 10; *pptr = &q; } int main() { int r = 20; int *p = &r; fun(&p); printf("%d", *p); return 0; } In the above example, the function fun() expects a double pointer (pointer to a pointer to an integer). Fun() modifies the value at address pptr. The value at address pptr is pointer p as we pass adderess of p to fun(). In fun(), value at pptr is changed to address of q. Therefore, pointer p of main() is changed to point to a new variable q. Also, note that the program won’t cause any out of scope problem because q is a static variable. Static variables exist in memory even after functions return. For an auto variable, we might have seen some unexpected output because auto variable may not exist in memory after functions return.Quiz of this Question Advanced Pointer C-Advanced Pointer C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 Output of C programs | Set 64 (Pointers)
[ { "code": null, "e": 24073, "s": 24045, "text": "\n28 Jun, 2021" }, { "code": "void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); return 0; }", "e": 24212, "s": 24073, "text": null }, { "code": null, "e": 24646, "s": 24212, "text": "(A) 10(B) 20(C) Compiler error(D) Runtime ErrorAnswer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local pointer of one function inside another function, then we must pass pointer to the pointer. By passing the pointer to the pointer, we can change pointer to point to something else. See the following program as an example." }, { "code": null, "e": 24796, "s": 24646, "text": "void fun(int **pptr)\n{\n static int q = 10;\n *pptr = &q;\n}\n\nint main()\n{\n int r = 20;\n int *p = &r;\n fun(&p);\n printf(\"%d\", *p);\n return 0;\n}\n\n" }, { "code": null, "e": 25143, "s": 24796, "text": "In the above example, the function fun() expects a double pointer (pointer to a pointer to an integer). Fun() modifies the value at address pptr. The value at address pptr is pointer p as we pass adderess of p to fun(). In fun(), value at pptr is changed to address of q. Therefore, pointer p of main() is changed to point to a new variable q." }, { "code": null, "e": 25457, "s": 25143, "text": "Also, note that the program won’t cause any out of scope problem because q is a static variable. Static variables exist in memory even after functions return. For an auto variable, we might have seen some unexpected output because auto variable may not exist in memory after functions return.Quiz of this Question" }, { "code": null, "e": 25474, "s": 25457, "text": "Advanced Pointer" }, { "code": null, "e": 25493, "s": 25474, "text": "C-Advanced Pointer" }, { "code": null, "e": 25504, "s": 25493, "text": "C Language" }, { "code": null, "e": 25511, "s": 25504, "text": "C Quiz" }, { "code": null, "e": 25609, "s": 25511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25618, "s": 25609, "text": "Comments" }, { "code": null, "e": 25631, "s": 25618, "text": "Old Comments" }, { "code": null, "e": 25666, "s": 25631, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 25694, "s": 25666, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25740, "s": 25694, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25752, "s": 25740, "text": "fork() in C" }, { "code": null, "e": 25784, "s": 25752, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25826, "s": 25784, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25869, "s": 25826, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25900, "s": 25869, "text": "C | File Handling | Question 1" }, { "code": null, "e": 25922, "s": 25900, "text": "C | Misc | Question 7" } ]
Calculate the curl of a vector field in Python and plot it with Matplotlib
To calculate the curl of a vector field in Python and plot in with Matplotlib, we can use quiver() method and calculate the corresponding data. Set the figure size and adjust the padding between and around the subplots. Create a new figure or activate an existing figure using figure() method. Add a 3D axes to the figure as part of a subplot arrangement. Create x, y and z data points using numpy meshgrid. Create u, v and w data curl vector positions. Use quiver() method to get vectors. Turn off the axes. To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = fig.add_subplot(projection='3d') x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2), np.arange(-0.8, 1, 0.2), np.arange(-0.8, 1, 0.8)) u = 0 v = y**2 w = -2*y*z - y ax.quiver(x, y, z, u, v, w, length=0.1) ax.axis('off') plt.show()
[ { "code": null, "e": 1206, "s": 1062, "text": "To calculate the curl of a vector field in Python and plot in with Matplotlib, we can use quiver() method and calculate the corresponding data." }, { "code": null, "e": 1282, "s": 1206, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1356, "s": 1282, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1418, "s": 1356, "text": "Add a 3D axes to the figure as part of a subplot arrangement." }, { "code": null, "e": 1470, "s": 1418, "text": "Create x, y and z data points using numpy meshgrid." }, { "code": null, "e": 1516, "s": 1470, "text": "Create u, v and w data curl vector positions." }, { "code": null, "e": 1552, "s": 1516, "text": "Use quiver() method to get vectors." }, { "code": null, "e": 1571, "s": 1552, "text": "Turn off the axes." }, { "code": null, "e": 1613, "s": 1571, "text": "To display the figure, use show() method." }, { "code": null, "e": 2050, "s": 1613, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\n\nax = fig.add_subplot(projection='3d')\n\nx, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),\n np.arange(-0.8, 1, 0.2),\n np.arange(-0.8, 1, 0.8))\n\nu = 0\nv = y**2\nw = -2*y*z - y\n\nax.quiver(x, y, z, u, v, w, length=0.1)\nax.axis('off')\n\nplt.show()" } ]
Tryit Editor v3.7
Tryit: HTML border collapse
[]
5 Code Knowledge Points About Python TimeDelta | Towards Data Science
As one of the most important built-in libraries in Python, the “datetime” library is a must-learn for any Python learners. In this library, “timedelta” which indicates a time interval, is the module that I like the most. It provides many useful functions that let us achieve features out-of-the-box, as well as enable the maximum flexibility of the usage patterns. It is no doubt that this library can be a “role module” for any developers which shows what is “Pythonic”. For such a common library, I’m sure that you must have ever used it or have already mastered it. However, there are still some “cold knowledge” regarding the “timedelta” module that you need to know. It may help you to save a lot of time during your development. Hope this article can help. from datetime import timedelta After imported this module, we can start the demonstration. You should know that it is very easy to define a time interval using timedelta. For example, timedelta(days=1) indicates a time interval that is exactly one day. However, do you know that timedelta actually have boundaries? We can check the boundaries as follows. timedelta.mintimedelta.max What if we want to define a time interval that exceeds the boundaries? Let’s try to add one day on the upper bound. timedelta(days=1) + timedelta.max As shown, Python will throw an overflow exception because timedelta is not designed to handle that large time intervals. How large it is? If we use 999999999 days divide 365 (roughly estimation ignores leap years), it is about 2.75 million years. Well, if we are not using timedelta to calculate something about the history of dinosaur, it would be well enough :) It is known that we can use days, hours, minutes, seconds and microseconds to define a time interval using timedelta. By the way, it makes sense that we can’t use the units more than days because a month may have 28–31 days and a year can have 365 or 366 days. However, we need to know that the resolution of timedelta is microseconds. This means that we cannot use timedelta to handle nanoseconds. Sorry to make physicist and chemists disappointed :) In fact, we can obtain this minimum resolution from the timedelta module by calling its attributes resolution. What if we try to have a time interval smaller than the resolution? Here is an example. We can try to get half of a microsecond. timedelta.resolution / 2 The timedelta object will simple become zero, which means that there is literally no time span in this “interval”. This is definitely true as we can prove it by trying to recover it back to one microsecond after splitting it. (timedelta(microseconds=1) / 2) * 2 It is still zero because when we divide it, we lost it. In the implementation of the timedelta object, days, hours, minutes, seconds and microseconds are class attributes. These attributes will have their own valid ranges. This definitely makes sense because we know that 1 day has only 24 hours and 1 hour contains 60 minutes. However, even if we define timedelta object that excesses the range, we will neither trigger the overflow exception nor lose the exceeded part. It will be automatically converted into higher or lower units. For example, if we define an interval with 1000000 microseconds, which is exactly 1 second, we will simply get an interval that equals 1 second. one_second = timedelta(microseconds=999999 + 1) If we define an interval using seconds attribute only and make it exceeds 1 day, timedelta will handle it very well. one_day_and_one_second = timedelta(seconds=86401) However, the attribute seconds is a primary attribute that has a higher priority in timedelta. That means as long as the interval is less than one day, timedelta will use seconds to indicate it rather than using hours or minutes. three_thousands_six_hundred_seconds = timedelta(minutes=60) In this section, I want to show off how timedelta module is flexible. You can almost apply any types of numeric operations on timedelta objects. we have defined some objects in the previous section so that we can reuse them for demonstration. First of all, it won’t be surprised that subtraction will work. one_day = one_day_and_one_second - one_second This also means that we can transform the equation just like the elements are numbers. assert one_day + one_second == one_day_and_one_secondassert one_day_and_one_second - one_day == one_second We can multiply or divide the time intervals using numbers. For example, 10 times 1 day will be 10 days. one_day * 10 We can divide the time interval by another. The example below shows “how many seconds does one day have”. one_day / one_second If we want an integer, the double slash also gives us a “floor” of the result. one_day // one_second We can even have modulo operations between timedelta objects. timedelta(seconds=5) % timedelta(seconds=2) Some numeric functions also can be applied on timedelta objects, such as getting absolute values. abs(timedelta(days=-7)) This will be very helpful when you are getting the “difference” between two datetime objects and don’t care which one is precedent. Sometimes, for comparing or storing purposes we may have to convert the time intervals into a unified time unit. Most of the time we can call total_seconds() function to “flatten” a timedelta object into seconds. one_day.total_seconds() This is actually equivalent to one_day / timedelta(seconds=1). Therefore, we can easily flatten a timedelta object into other time units. For example: one_day / timedelta(hours=1)one_day / timedelta(microseconds=1) Finally, not only a datetime object can be easily converted to a string for output purposes, but a timedelta object can also be. str(timedelta(days=7, hours=10, seconds=30, microseconds=300000)) It may not be exactly what you are expecting, since we will have different requirements for the application that we develop every time. However, it definitely a valid way of output a time interval. Also, we can always use the class function repr() to output the object as a string. repr(timedelta(days=7, hours=10, seconds=30, microseconds=300000)) In this article, I presume you have already know the timedelta module in the datetime library that is built-in to Python. I’ve tried to organise some knowledge points that are not likely to be known by every developer, especially the learners and explained in this article, such as the boundaries and rare operations between the objects. Hope it satisfies some of your curiosity. 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": 644, "s": 172, "text": "As one of the most important built-in libraries in Python, the “datetime” library is a must-learn for any Python learners. In this library, “timedelta” which indicates a time interval, is the module that I like the most. It provides many useful functions that let us achieve features out-of-the-box, as well as enable the maximum flexibility of the usage patterns. It is no doubt that this library can be a “role module” for any developers which shows what is “Pythonic”." }, { "code": null, "e": 935, "s": 644, "text": "For such a common library, I’m sure that you must have ever used it or have already mastered it. However, there are still some “cold knowledge” regarding the “timedelta” module that you need to know. It may help you to save a lot of time during your development. Hope this article can help." }, { "code": null, "e": 966, "s": 935, "text": "from datetime import timedelta" }, { "code": null, "e": 1026, "s": 966, "text": "After imported this module, we can start the demonstration." }, { "code": null, "e": 1188, "s": 1026, "text": "You should know that it is very easy to define a time interval using timedelta. For example, timedelta(days=1) indicates a time interval that is exactly one day." }, { "code": null, "e": 1290, "s": 1188, "text": "However, do you know that timedelta actually have boundaries? We can check the boundaries as follows." }, { "code": null, "e": 1317, "s": 1290, "text": "timedelta.mintimedelta.max" }, { "code": null, "e": 1433, "s": 1317, "text": "What if we want to define a time interval that exceeds the boundaries? Let’s try to add one day on the upper bound." }, { "code": null, "e": 1467, "s": 1433, "text": "timedelta(days=1) + timedelta.max" }, { "code": null, "e": 1714, "s": 1467, "text": "As shown, Python will throw an overflow exception because timedelta is not designed to handle that large time intervals. How large it is? If we use 999999999 days divide 365 (roughly estimation ignores leap years), it is about 2.75 million years." }, { "code": null, "e": 1831, "s": 1714, "text": "Well, if we are not using timedelta to calculate something about the history of dinosaur, it would be well enough :)" }, { "code": null, "e": 2092, "s": 1831, "text": "It is known that we can use days, hours, minutes, seconds and microseconds to define a time interval using timedelta. By the way, it makes sense that we can’t use the units more than days because a month may have 28–31 days and a year can have 365 or 366 days." }, { "code": null, "e": 2283, "s": 2092, "text": "However, we need to know that the resolution of timedelta is microseconds. This means that we cannot use timedelta to handle nanoseconds. Sorry to make physicist and chemists disappointed :)" }, { "code": null, "e": 2394, "s": 2283, "text": "In fact, we can obtain this minimum resolution from the timedelta module by calling its attributes resolution." }, { "code": null, "e": 2523, "s": 2394, "text": "What if we try to have a time interval smaller than the resolution? Here is an example. We can try to get half of a microsecond." }, { "code": null, "e": 2548, "s": 2523, "text": "timedelta.resolution / 2" }, { "code": null, "e": 2774, "s": 2548, "text": "The timedelta object will simple become zero, which means that there is literally no time span in this “interval”. This is definitely true as we can prove it by trying to recover it back to one microsecond after splitting it." }, { "code": null, "e": 2810, "s": 2774, "text": "(timedelta(microseconds=1) / 2) * 2" }, { "code": null, "e": 2866, "s": 2810, "text": "It is still zero because when we divide it, we lost it." }, { "code": null, "e": 3033, "s": 2866, "text": "In the implementation of the timedelta object, days, hours, minutes, seconds and microseconds are class attributes. These attributes will have their own valid ranges." }, { "code": null, "e": 3345, "s": 3033, "text": "This definitely makes sense because we know that 1 day has only 24 hours and 1 hour contains 60 minutes. However, even if we define timedelta object that excesses the range, we will neither trigger the overflow exception nor lose the exceeded part. It will be automatically converted into higher or lower units." }, { "code": null, "e": 3490, "s": 3345, "text": "For example, if we define an interval with 1000000 microseconds, which is exactly 1 second, we will simply get an interval that equals 1 second." }, { "code": null, "e": 3538, "s": 3490, "text": "one_second = timedelta(microseconds=999999 + 1)" }, { "code": null, "e": 3655, "s": 3538, "text": "If we define an interval using seconds attribute only and make it exceeds 1 day, timedelta will handle it very well." }, { "code": null, "e": 3705, "s": 3655, "text": "one_day_and_one_second = timedelta(seconds=86401)" }, { "code": null, "e": 3935, "s": 3705, "text": "However, the attribute seconds is a primary attribute that has a higher priority in timedelta. That means as long as the interval is less than one day, timedelta will use seconds to indicate it rather than using hours or minutes." }, { "code": null, "e": 3995, "s": 3935, "text": "three_thousands_six_hundred_seconds = timedelta(minutes=60)" }, { "code": null, "e": 4238, "s": 3995, "text": "In this section, I want to show off how timedelta module is flexible. You can almost apply any types of numeric operations on timedelta objects. we have defined some objects in the previous section so that we can reuse them for demonstration." }, { "code": null, "e": 4302, "s": 4238, "text": "First of all, it won’t be surprised that subtraction will work." }, { "code": null, "e": 4348, "s": 4302, "text": "one_day = one_day_and_one_second - one_second" }, { "code": null, "e": 4435, "s": 4348, "text": "This also means that we can transform the equation just like the elements are numbers." }, { "code": null, "e": 4542, "s": 4435, "text": "assert one_day + one_second == one_day_and_one_secondassert one_day_and_one_second - one_day == one_second" }, { "code": null, "e": 4647, "s": 4542, "text": "We can multiply or divide the time intervals using numbers. For example, 10 times 1 day will be 10 days." }, { "code": null, "e": 4660, "s": 4647, "text": "one_day * 10" }, { "code": null, "e": 4766, "s": 4660, "text": "We can divide the time interval by another. The example below shows “how many seconds does one day have”." }, { "code": null, "e": 4787, "s": 4766, "text": "one_day / one_second" }, { "code": null, "e": 4866, "s": 4787, "text": "If we want an integer, the double slash also gives us a “floor” of the result." }, { "code": null, "e": 4888, "s": 4866, "text": "one_day // one_second" }, { "code": null, "e": 4950, "s": 4888, "text": "We can even have modulo operations between timedelta objects." }, { "code": null, "e": 4994, "s": 4950, "text": "timedelta(seconds=5) % timedelta(seconds=2)" }, { "code": null, "e": 5092, "s": 4994, "text": "Some numeric functions also can be applied on timedelta objects, such as getting absolute values." }, { "code": null, "e": 5116, "s": 5092, "text": "abs(timedelta(days=-7))" }, { "code": null, "e": 5248, "s": 5116, "text": "This will be very helpful when you are getting the “difference” between two datetime objects and don’t care which one is precedent." }, { "code": null, "e": 5461, "s": 5248, "text": "Sometimes, for comparing or storing purposes we may have to convert the time intervals into a unified time unit. Most of the time we can call total_seconds() function to “flatten” a timedelta object into seconds." }, { "code": null, "e": 5485, "s": 5461, "text": "one_day.total_seconds()" }, { "code": null, "e": 5636, "s": 5485, "text": "This is actually equivalent to one_day / timedelta(seconds=1). Therefore, we can easily flatten a timedelta object into other time units. For example:" }, { "code": null, "e": 5700, "s": 5636, "text": "one_day / timedelta(hours=1)one_day / timedelta(microseconds=1)" }, { "code": null, "e": 5829, "s": 5700, "text": "Finally, not only a datetime object can be easily converted to a string for output purposes, but a timedelta object can also be." }, { "code": null, "e": 5895, "s": 5829, "text": "str(timedelta(days=7, hours=10, seconds=30, microseconds=300000))" }, { "code": null, "e": 6093, "s": 5895, "text": "It may not be exactly what you are expecting, since we will have different requirements for the application that we develop every time. However, it definitely a valid way of output a time interval." }, { "code": null, "e": 6177, "s": 6093, "text": "Also, we can always use the class function repr() to output the object as a string." }, { "code": null, "e": 6244, "s": 6177, "text": "repr(timedelta(days=7, hours=10, seconds=30, microseconds=300000))" }, { "code": null, "e": 6624, "s": 6244, "text": "In this article, I presume you have already know the timedelta module in the datetime library that is built-in to Python. I’ve tried to organise some knowledge points that are not likely to be known by every developer, especially the learners and explained in this article, such as the boundaries and rare operations between the objects. Hope it satisfies some of your curiosity." }, { "code": null, "e": 6635, "s": 6624, "text": "medium.com" } ]